admin管理员组文章数量:1288019
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.
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.
Share Improve this question edited Dec 25, 2018 at 15:25 Billal BEGUERADJ 22.8k45 gold badges123 silver badges140 bronze badges asked Dec 25, 2018 at 15:08 RomitRomit 771 silver badge8 bronze badges 02 Answers
Reset to default 11Let 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);
}
});
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.
linebyline npm package
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
});
本文标签: javascriptReturning the line of a searched text from a file using nodejsStack Overflow
版权声明:本文标题:javascript - Returning the line of a searched text from a file using node.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741334980a2372989.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论