How to check if a file contains a string using 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.
  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.

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.