How to Replace a String in a File using Node.js

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
4 min

banner

# 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} = 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); }); });
The code for this article is available on GitHub

Note: if you use the ES6 import/export syntax, use the following import statement instead.

index.js
import {readFile, writeFile, writeFileSync, promises as fsPromises} from 'fs';

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 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 bobbyhadz.com

After running the node index.js command, the example.txt file looks as follows:

replace string in file using node js

The code for this article is available on GitHub

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.
index.js
const replaced = contents.replace(/to be replaced/g, '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 will only replace the first occurrence of the string in the file.

# Replace a String in a File ignoring the case

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 code for this article is available on GitHub

Note: if you use the ES6 import/export syntax, use the following import statement instead.

index.js
import { readFile, writeFile, writeFileSync, promises as fsPromises, } from 'fs';

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.

# Replace a String in a File using Promises

To replace a string in a file asynchronously:

  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 {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 code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev