To check if a file contains a string in Node.js:
- Use the
fsPromises.readFile()method from native file system module (fs) to read the file. - Use the
includes()method to check if the string is present in the file. - The
includes()method will returntrueif the matching string is contained in the file. Otherwise,falseis returned.
Note: Since
fsis a native module, you do not need to install it. Just import thefsPromisesobject in your code by callingconst 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 aBufferobject. 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.