HTML file as a variable in Node.js

mik*_*098 0 html node.js sendgrid

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);
Run Code Online (Sandbox Code Playgroud)

Then I'm sending the email with Sendgrid as a HTML.

var content = new helper.Content('text/html', messageContent);
Run Code Online (Sandbox Code Playgroud)

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?

qry*_*qry 5

如果我理解这个问题,还不能确定,但​​是您可以非常简单地阅读文件。只是

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

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

如果保持简单,则可以只使用一种正则表达式,然后将其替换为值。如果必须更复杂,我建议您使用模板引擎。我个人的喜好是胡须。还有一个用于髭的nodejs的库,称为Mustache。在这种情况下,您可以这样使用它:

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

为此,您必须先了解胡须,但这确实很简单。在这里查看教程

然后,您的file.html应该如下所示:

<div> lat: {{formatted.latitude}} <br> lng: {{formatted.longitude}} </div>
<script>
     var formattedDate = "{{formattedDate}}";
</script>
Run Code Online (Sandbox Code Playgroud)

注意您必须先使用npm install mustache来安装mustache