HTML file as a variable in Node.js

html, node.js, sendgrid

Solution

Not shure if i understood the question, but you can read the file really simple. Just

var fs = require('fs'); //Filesystem    

var content = fs.readFileSync("path/to/File/file.html","utf-8");
//this is the content of your file.html

if you keep it simple, you could just use a type of regular expression and replace something with the value.. If it has to be more complex, i would recommend you using a template engine. My personal preference is mustache. There is also a libary for nodejs of mustache, called Mustache. In this case you use it like this:

const mustache   = require('mustache');
const fs = require('fs'); //Filesystem    
//...
var content = fs.readFileSync("path/to/File/file.html","utf-8");
var view = {formatted:{latitude: 0,longitude:0}, formattedDate:"01/01/1990"}
var output = mustache.render(content, view);

For doing this, you have to understand mustache first, but it is really simple. See a tutorial here

Your file.html then should look like this:

<div> lat: {{formatted.latitude}} <br> lng: {{formatted.longitude}} </div>
<script>
     var formattedDate = "{{formattedDate}}";
</script>

Note you have to install mustache with `npm install mustache` first

Problem

I need to send something as a html via email (I'm using Sendgrid) with simple Node.js server. I'm just sending some text with variables in them and line breaks. ``` var postData = 'lat: ' + formatted.latitude + '<br>lng: ' + formatted.longitude + '<br>time: ' + formattedDate; sendEmail(postData); ``` Then I'm sending the email with Sendgrid as a HTML. ``` var content = new helper.Content('text/html', messageContent); ``` No need to paste remaining blocks of code. What I need is more complex .html file with css and javascript in it. Moreover I need to change some values in it. What is the easiest way to assign this file to variable and send it like this?

Original source