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.
  2. Use the includes() method to check if the string is present 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').

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. So we have to await 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:

contents.toLowerCase().includes(text.toLowerCase())

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

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

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