# How to check if a file contains a string using Node.js

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

> Learn how to use the native fs module to check if a file contains a string in Node.js.

To check if a file contains a string in Node.js:

1. Use the `fsPromises.readFile()` method from native file system module (`fs`) to [read the file](https://attacomsian.com/blog/reading-writing-files-nodejs#reading-from-files).
2. Use the `includes()` method to [check if the string is present](https://attacomsian.com/blog/javascript-includes-method) in the file.
3. The `includes()` method will return `true` if the matching string is contained in the file. Otherwise, `false` is returned.

> **Note:** Since `fs` is a native module, you do not need to install it. Just import the `fsPromises` object in your code by calling `const fsPromises = require('fs/promises')`.

```javascript
const fsPromises = require('fs/promises')

const fileChecker = async (filename, text) => {
  try {
    const contents = await fsPromises.readFile(filename, 'utf-8')

    return contents.includes(text)
  } catch (err) {
    console.error(err)
  }

  return false
}

fileChecker('file.txt', 'welcome')
```

The `fsPromises.readFile()` function asynchronously reads the entire contents of a file and returns a [promise](https://attacomsian.com/blog/promises-javascript). So we have to [`await`](https://attacomsian.com/blog/async-await-javascript) to get the resolved string.

> The second parameter of `fsPromises.readFile()` is the file encoding. If skipped, the method returns a `Buffer` object. Otherwise, a string is returned.

The `includes()` method is case-sensitive, which means it acts differently to both uppercase and lowercase characters.

If you want to perform a case-insensitive search, convert the file's contents and the matching text to [lowercase](https://attacomsian.com/blog/javascript-string-uppercase-lowercase):


```javascript
contents.toLowerCase().includes(text.toLowerCase())
```

To read the file contents synchronously, use the `fs.readFileSync()` method instead, as shown below:

```javascript
const fs = require('fs')

const fileChecker = (filename, text) => {
  const contents = fs.readFileSync(filename, 'utf-8')

  return contents.toLowerCase().includes(text.toLowerCase())
}

fileChecker('file.txt', 'welcome')
```
