Replace string in a text file in node.js

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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Solution 2

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.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply