Check if a File contains a String in Node.js

avatar

Borislav Hadzhiev

Last updated: Mar 28, 2022

banner

Photo from Unsplash

Check if a File contains a String in Node.js #

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

  1. Use the fs.readFileSync() method to read the file.
  2. Use the includes() method to check if the string is contained in the file.
  3. The includes method will return true if the string is contained in the file.
index.js
// 👇️ if using ES6 Imports // import {readFileSync, promises as fsPromises} from 'fs'; const {readFileSync, promises: fsPromises} = require('fs'); // ✅ read file SYNCHRONOUSLY function checkIfContainsSync(filename, str) { const contents = readFileSync(filename, 'utf-8'); const result = contents.includes(str); return result; } // 👇️ true console.log(checkIfContainsSync('./example.txt', 'hello')); // -------------------------------------------------------------- // ✅ read file ASYNCHRONOUSLY async function checkIfContainsAsync(filename, str) { try { const contents = await fsPromises.readFile(filename, 'utf-8'); const result = contents.includes(str); console.log(result); return result; } catch (err) { console.log(err); } } // 👇️ Promise<true> checkIfContainsAsync('./example.txt', 'hello');

The function from the first example reads the contents of a file synchronously.

The fs.readFileSync method takes the path to the file as the first parameter and the encoding as the second.

The method returns the contents of the provided path.

If you omit the encoding parameter, the function will return a buffer, otherwise a string is returned.

We used the String.includes method to check if the file's contents contain the provided string.

The includes method performs a case-sensitive search for whether the provided string is found in another string.

If you need to do a case-insensitive search, convert the file's contents and the passed in string to lowercase.

index.js
// 👇️ if using ES6 Imports // import {readFileSync, promises as fsPromises} from 'fs'; const {readFileSync, promises: fsPromises} = require('fs'); // ✅ read file SYNCHRONOUSLY function checkIfContainsSync(filename, str) { const contents = readFileSync(filename, 'utf-8'); // 👇️ convert both to lowercase for case insensitive check const result = contents.toLowerCase().includes(str.toLowerCase()); return result; } // 👇️ true console.log(checkIfContainsSync('./example.txt', 'HELLO'));
The code snippet above assumes that there is an example.txt file located in the same directory. Make sure to also open your terminal in that same directory.
example.txt
hello world one two three

The directory structure in the example assumes that the index.js file and the example.txt file are located in the same folder and our terminal is also in that folder.

Alternatively, you could use the fsPromises object to read a file asynchronously.

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

  1. Use the fsPromises.readFile() method to read the file.
  2. Use the includes() method to check if the string is contained in the file.
  3. The includes method will return true if the string is contained in the file.
index.js
// 👇️ if using ES6 Imports // import {readFileSync, promises as fsPromises} from 'fs'; const {readFileSync, promises: fsPromises} = require('fs'); // ✅ read file ASYNCHRONOUSLY async function checkIfContainsAsync(filename, str) { try { const contents = await fsPromises.readFile(filename, 'utf-8'); const result = contents.includes(str); console.log(result); return result; } catch (err) { console.log(err); } } checkIfContainsAsync('./example.txt', 'hello');

The fsPromises.readFile() method asynchronously reads the contents of the provided file.

If you don't provide a value for the encoding parameter, the method returns a buffer, otherwise a string is returned.

The method returns a promise that fulfills with the contents of the file, so we have to await it or use the .then() method on it to get the resolved string.

Note that the checkIfContainsAsync function returns a Promise that resolves with a boolean value.

It doesn't return a boolean value directly like the synchronous method from the first code snippet.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.