I am using node.js. I want to read a file with some placeholder strings and replace them dynamically before I serve the file. This is not an HTML file, so a templating engine will not work.
How can I do this?
I am using node.js. I want to read a file with some placeholder strings and replace them dynamically before I serve the file. This is not an HTML file, so a templating engine will not work.
How can I do this?
If a template engine is overkill just use string.replace().
temp = "Hello %NAME%, would you like some %DRINK%?";
temp = temp.replace("%NAME%","Michael Dillon");
temp = temp.replace("%DRINK%","tea");
console.log(temp);
With only a bit more work you could make a general purpose template function based on just the standard methods in the String object.
Templating engines are not only for html. If you are using Express, for instance, you can set your own headers and specify a content-type:
View:
var foo = "{{ bar }}";
Rendering:
app.get('/file.js', function(req, res, next) {
res.render('templateName', {
locals: {bar: 'quux'},
headers: {'content-type': 'text/javascript'}
});
})
Will yield:
var foo = "quux";
If you are not using Express, you can just render the template and send the response with any content-type you like.