Search code examples
node.jsejsreadfiletemplate-engine

How to read dynamic html file(template engine) using node.js


So there are two cases:

  1. I have created a template engine(.ejs file) and I'm able to render it to browser.

    app.get('/htmlTemplate', (req, res) => {
       res.render('banner', { qs: req.query }) 
    });
    
  2. I have a static html file and I'm able to read it using node js

app.set('view engine', 'ejs');

app.get('/staticHTML', (req, res) => {
    fs.readFile("views/banner.html", 'UTF-8', function (error, pgResp) {
        console.log(pgResp);
        resp.end();
    });
});

But now my problem here is that I need a mix of these two cases instead of rendering a .ejs file, I want read/fetch it along with dynamic value and store it in a variable, so that I can pass that dynamic html file to another api.

So I want something like this:

app.set('view engine', 'ejs');

app.get('/htmlTemplate', (req, res) => {
  fs.readFile('banner', { qs: req.query }, 'UTF-8', function (error, pgResp){
    console.log(pgResp);
  });
});

Is it possible to do so? If yes, then how can I achieve it?


Solution

  • Use ejs.renderFile :

    ejs.renderFile(__dirname + "/../...path...",{key: value}, function (err, str) {
        // str => Rendered HTML string
        console.log("html: ", str);
    });