Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML file as a variable in Node.js

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?

like image 321
mikro098 Avatar asked Sep 17 '26 10:09

mikro098


1 Answers

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

like image 92
qry Avatar answered Sep 19 '26 01:09

qry