Replace a String in a File using Node.js

avatar

Borislav Hadzhiev

Last updated: Aug 30, 2022

banner

Photo from Unsplash

Replace a String in a File using Node.js #

To replace a string in a file in Node.js:

  1. Use the fs.readFile() method to read the file.
  2. Use the replace() method to replace the string with the replacement.
  3. Write the result to the file using the fs.writeFile() method.
index.js
// 👇️ if using ES6 imports uncomment next line // import {readFile, writeFile, writeFileSync, promises as fsPromises} from 'fs'; const {readFile, writeFile, promises: fsPromises} = require('fs'); readFile('./example.txt', 'utf-8', function (err, contents) { if (err) { console.log(err); return; } const replaced = contents.replace(/to be replaced/g, 'replacement string'); writeFile('./example.txt', replaced, 'utf-8', function (err) { console.log(err); }); });

We used the fs.readFile method to read the contents of the file.

The first parameter we passed to the method is the path to the file and the second is the encoding.

If you omit the encoding parameter, the function will return a buffer, otherwise, a string is returned.

The callback function gets called with an error object or null (if there is no error) and the contents of the file.

The code snippet above assumes that there is an example.txt file located in the same directory. Make sure to also open your terminal in that same directory.
example.txt
to be replaced to be replaced to be replaced

We used the String.replace method to replace a string in the file.

The first parameter we passed to the replace method is a regular expression and the second is the replacement string.

The forward slashes / / mark the beginning and end of the regular expression.

The g flag stands for global and replaces all occurrences of the matched string.

If you omit the g flag, you would only replace the first occurrence of the string in the file.

If you want to perform a case-insensitive match, use the i flag as well.

index.js
// 👇️ if using ES6 imports uncomment next line // import {readFile, writeFile, writeFileSync, promises as fsPromises} from 'fs'; const {readFile, writeFile, promises: fsPromises} = require('fs'); readFile('./example.txt', 'utf-8', function (err, contents) { if (err) { console.log(err); return; } // 👇️ match string case-insensitively 👇️ const replaced = contents.replace(/to be replaced/gi, 'replacement string'); writeFile('./example.txt', replaced, 'utf-8', function (err) { console.log(err); }); });

The i flag stands for ignore and does a case-insensitive search in string.

The fs.writeFile function is then used to write the updated string to the file.

The example above assumes that the code is placed in a .js file and looks for an example.txt file. Make sure to open your terminal in the same directory and run the file with node index.js.

Alternatively, you can use promises.

To replace a string in a file in Node.js:

  1. Use the fsPromises.readFile() method to read the file.
  2. Use the replace() method to replace the string with the replacement.
  3. Write the result to the file using the fsPromises.writeFile() method.
index.js
// 👇️ if using ES6 imports uncomment next line // import {readFile, writeFile, writeFileSync, promises as fsPromises} from 'fs'; const {readFile, writeFile, promises: fsPromises} = require('fs'); async function replaceInFile(filename, replacement) { try { const contents = await fsPromises.readFile(filename, 'utf-8'); const replaced = contents.replace(/to be replaced/gi, replacement); await fsPromises.writeFile(filename, replaced); } catch (err) { console.log(err); } } replaceInFile('./example.txt', 'replacement string 🎊');

This approach achieves the same result. However, this code sample uses promises instead of callbacks.

The fsPromises.readFile() method asynchronously reads the contents of the provided file.

If you don't provide a value for the encoding parameter, the method returns a buffer, otherwise a string is returned.

The method returns a promise that resolves with the contents of the file, so we have to await it or use the .then() method to get the resolved string.

The fsPromises.writeFile method asynchronously writes data to a file replacing the file's contents if the file already exists.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.