'Returning the line of a searched text from a file using node.js
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.
Solution 1:[1]
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
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RAZ0229 |
