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

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 4, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/nodejs-replace-string-in-file

> Learn how to use the File System (fs) module in Node.js to replace all occurrences of a string in a file.

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](https://attacomsian.com/blog/reading-writing-files-nodejs#reading-from-files) 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 &mdash; read file contents into a string:

```javascript
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](https://attacomsian.com/blog/string-replace-javascript) with the given string:

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

We used the regular expressions `i` and `g` [global modifiers](https://attacomsian.com/blog/javascript-regular-expressions#regular-expression-modifiers) to perform a global case-insensitive replacement. 

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

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