I am using fs to read the contents of a file, and then searching for a particular word within that file, if the file contains that word instead of returning boolean or the word, I want the output the line that contains the keyword. How do I output that entire line?
const fs = require("fs");
let file = fs.readFileSync("read.txt", "utf8");
if(file.indexOf("keyword") >= 0) {
console.log("Line of the keyword");
}
I only want the console.log() to output the line if that line contains the keyword.
readFileSync method, you will get a Buffer. Convert the Buffer into string Using the toString( ) method. Now use the String. split() method to break the data and the delimiter should be “\n”
Let us first try splitting the string from the file by the new lines. Then the resulting array can be searched for the occurrence of the keyword. If search is successful, print the index of the array which is same as the line number.
const fs = require("fs");
let file = fs.readFileSync("read.txt", "utf8");
let arr = file.split(/\r?\n/);
arr.forEach((line, idx)=> {
if(line.includes("keyword")){
console.log((idx+1)+':'+ line);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With