Last updated: Apr 5, 2024
Reading timeยท4 min
To replace a string in a file in Node.js:
fs.readFile()
method to read the file.replace()
method to replace the string with the replacement.fs.writeFile()
method.// ๐๏ธ 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); }); });
Note: if you use the ES6 import/export syntax, use the following import statement instead.
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.
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.
example.txt
file located in the same directory. Make sure to also open your terminal in that same directory.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:
We used the String.replace() method to replace a string in the file.
replace()
method is a regular expression and the second is the replacement string.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.
g
flag, you will 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.
// ๐๏ธ 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); }); });
Note: if you use the ES6 import/export syntax, use the following import statement instead.
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.
.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 asynchronously:
fsPromises.readFile()
method to read the file.replace()
method to replace the string with the replacement.fsPromises.writeFile()
method.// ๐๏ธ 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 ๐');
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.
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.
You can learn more about the related topics by checking out the following tutorials: