How to replace a string in a file using Node.js

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.