SJ19
SJ19

Reputation: 2123

Javascript / Node.js importing html file and passing parameters to html file

I'm making a node.js server which sends emails on demand. I'm importing an html file, which I assign to "output". This is then emailed to the receiver.

app.post("/send", (req, res) => {
    console.log("sending email...");
    const token = req.body.data.token;
    const output = fs.readFileSync('emailcontents.html').toString();

This works. But what would be the best way to pass the "token" variable to emailcontents.html?

Upvotes: 1

Views: 1083

Answers (1)

Jack Yu
Jack Yu

Reputation: 2425

If I misunderstand your requirement, please let me know. I'll do my best to modify the answer.

According to the conversation in comments, we could know you want to send a email to the user instead of using res.render to render emailcontents.html content for user in browser.
That email should contain the token.
And you want to insert token into your emailcontents.html instead appending.

We assume your html content look like this.

<h1>weclome here</h1>
<p> Please use this token to do something</p>.

You want to insert token into {here}.

<h1>weclome here</h1>
<p> Please use this {here} to do something</p>.

instead of {here}.

<h1>weclome here</h1>
<p> Please use this token to do something</p>. {here}

According above the requirement, I come up with two options.

First one, use replace method.

Before use this method, you need to modify your html like this.

<h1> this is emailcontents.html content</h1>
<h1>{token}</h1>

Then use replace method to replace {token}.

app.post("/send", (req, res) => {
    console.log("sending email...");
    const token = req.body.data.token;
    fs.readFile('emailcontents.html', (err, data) => {
        const output = data.toString().replace("{token}", token)
        // do other send mail job
    })

Note: you could use replace only when your html is very very very simple.

If your html is this, it's more complicated to handle it.
In this situation, I'll recommend you use second solution.

<h1>weclome here</h1>
<h1>{token}: {token}</h1>

Second, use template engine

You could use template engine to pass parameter, such as ejs.
It could work in any case.

<!-- emailcontents.ejs -->
<h1>this is emailcontents.html content</h1>
<h1>Please use this <%= token %> to do something</h1>
const ejs = require("ejs")
app.post("/send", (req, res) => {
    console.log("sending email...");
    const token = req.body.data.token;
    ejs.renderFile("./emailcontents.ejs", {token: token}, (error, output) => {
        // output is html string with token which you provide
        // do send mail job
    })

Upvotes: 2

Related Questions