. Advertisement .
..3..
. Advertisement .
..4..
Sometimes, you need to replace a string in a file in Node.js to make the code more readable. Or, this practice is vital to compare the results of different operating codes.
The following tutorial will introduce you to the easiest method to replace a string in a specific file.
How To Replace A String In A File Using Node.js
There are three main steps to replace a string in a file in Node.js:
Step 1: Read The File’s Content To A String By Using The ‘fs.readFile()’ Function
It is worth noting that ‘fs’ is a native module, thus you don’t have to install it. All you have to do is to call const fs = require(‘fs’) to import the function in your code.
const fs = require('fs')
fs.readFile('file.txt', 'utf-8', (err, contents) => {
if (err) {
return console.error(err)
}
console.log(contents)
})
Before replacing a string, you need to read the contents into it as the above example. Here, two parameters will be passed to fs.readFile(). They are the encoding and the path to the file. The first one is optional. Yet, if you skip this one, instead of a string, a buffer will be returned in the callback function.
The second parameter is often an error object. It is called null if there is no content or error in the file.
Step 2: Use The replace() Method
The replace() function is designed to replace all the string’s occurrences with a given string:
const updated = contents.replace(/example/gi, 'example two')
This one will search for a regular expression or a value in a string. Most of the time, the regular i and g expressions are used to perform an insensitive replacement.
The replace() function comes with two parameters. The searchValue is required with the regular expression and value as mentioned above. The newValue parameter is also compulsory, so you need to add the new value. This way, the replace() can replace the original values.
Then, the function will return a new string with the replaced values. There is no need to worry about the content, as the replace() doesn’t modify or change the original string.
Step 3: Use The writeFile()
After replacing the string, you can write the changes to the file with the writeFile() function:
const fs = require('fs')
// Read file into a string
fs.readFile('file.txt', 'utf-8', (err, contents) => {
if (err) {
return console.error(err)
}
// Replace string occurrences
const updated = contents.replace(/example/gi, 'example two')
// Write back to file
fs.writeFile('file.txt', updated, 'utf-8', err2 => {
if (err2) {
console.log(err2)
}
})
})
This example doesn’t make use of callbacks, it employs promises. The fspromises.readFile() can read the provided file’s content asynchronously.
It returns a promise fulfilling all the file’s contents. Thus, you need to use .then() function or await it to get the final string.
Conclusion
Replacing a string in a file using node.js should be easy as pie. Check three steps mentioned in the article to get the task done.
Leave a comment