Replace a String in a File using Node.js

avatar

Borislav Hadzhiev

Mon Mar 28 20223 min read

banner

Photo by Du Wei

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 - 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 - 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 🎊');

The approach is the same, however this example 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 fulfills with the contents of the file, so we have to await it or use the .then() method on it 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.