Akash Babu
Akash Babu

Reputation: 247

How to pass paramters to HTML file in node.js?

I have a code like res.sendfile('./home.html',{user:req.user}) and I want to access the user parameter in the HTML file. I don't want to use a template engine. How do I do this?

Upvotes: 0

Views: 118

Answers (1)

Tracker1
Tracker1

Reputation: 19334

If you don't want to use a template engine, you manually need to read in the file, then push whatever value you want into a placeholder...

var fs = require('fs');
...
  fs.readFile('./home.html', {encoding:'utf8'}, function(err, file){
    if (err) return res.end('ERROR');
    file = file.replace('%USER%', req.user);
    res.end(file);
  });

What you are describing is precisely what templates are for... now, if you want these variables to be available in JS.. then you may want a client "var cfg = %%CLIENT_CONFIG%%;" somewhere at the top, and you can JSON.stringify your config, and do the same replace.

If you want a lightweight templating engine you can use manually, you probably want to use lodash's template method.

Upvotes: 3

Related Questions