Reputation: 77
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.
Upvotes: 6
Views: 5877
Reputation: 180631
I know you are just looking to log out your results but it may be interesting to see another approach which includes writing to a file as well as using a package designed to read files line-by-line. It may be helpful in the future.
const readline = require("linebyline");
const fs = require('fs');
const rl = readline('sample.txt');
rl.on('line', function (line, lineCount, byteCount) {
console.log(lineCount); // this is not zero-based
// do something with the line of text
// line = line.substr(3).substr(0, 9); or whatever
if (line.includes("yourSearchTerm")) {
fs.appendFileSync('modified.txt', lineCount + ":" + line + '\n');
// or console.log(lineCount + ":" + line);
}
});
rl.on('error', function(e) {
// something went wrong
});
Upvotes: 0
Reputation: 16908
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);
}
});
Upvotes: 11