To replace a string in a file using Node.js, you can use the readFile() and writeFile() methods from the native fs module.

  1. Use the fs.readFile() method to read the file contents to a string.
  2. Use the replace() method to replace all occurrences of the string with the target string.
  3. Write the string back to the file using the fs.writeFile() method.

Note: Since fs is a native module, you do not need to install it. Just import it in your code by calling const fs = require('fs').

Let us start with the first step — read file contents into a string:

const fs = require('fs')

fs.readFile('file.txt', 'utf-8', (err, contents) => {
  if (err) {
    return console.error(err)
  }

  console.log(contents)
})

We passed two parameters to fs.readFile(): the path to the file and the encoding. The encoding parameter is optional. If skipped, the callback function will return a buffer, not a string.

The first parameter of the callback function is an error object. It is called with an error object or null if there is no error and the contents of the file.

Next, we use the replace() method to replace all occurrences of the string with the given string:

const updated = contents.replace(/example/gi, 'example two')

We used the regular expressions i and g global modifiers to perform a global case-insensitive replacement.

Finally, use the writeFile() method to write the changes back to the file as shown below:

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)
    }
  })
})

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.