How to replace a string in a file with Node.js?

Sometimes, we want to replace a string in a file with Node.js.

In this article, we’ll look at how to replace a string in a file with Node.js.

How to replace a string in a file with Node.js?

To replace a string in a file with Node.js, we can use the readFile and writeFile method.

For instance, we write

const fs = require('fs')

fs.readFile(someFile, 'utf8', (err, data) => {
  if (err) {
    return console.log(err);
  }
  const result = data.replace(/string to be replaced/g, 'replacement');

  fs.writeFile(someFile, result, 'utf8', (err) => {
    if (err) {
      return console.log(err);
    }
  });
});

to call fs.readFile at path someFile.

And we read it as 'utf8 encoded file.

In the callback we pass into readFile, we get the read file content from data.

Then we call data.replace with a regex that matches the text we want to replace and replace them with 'replacement'.

Next, we call fs.writeFile to write the new result to path someFile.

Conclusion

To replace a string in a file with Node.js, we can use the readFile and writeFile method.