Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 699
Sridatta Thatipamala Avatar asked Mar 01 '11 05:03

Sridatta Thatipamala


People also ask

What is replace in node JS?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

How do you change a line in a JavaScript file?

If you wish to add a new line to the JavaScript new line console while printing a few words, the \n sign for the new line can be used. JavaScript new line string manipulation is one of the things that is easy to learn, but difficult to master.

How do I write a node js file?

The fs. writeFile() method is used to asynchronously write the specified data to a file. By default, the file would be replaced if it exists. The 'options' parameter can be used to modify the functionality of the method.


1 Answers

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.

like image 115
Michael Dillon Avatar answered Sep 22 '22 23:09

Michael Dillon