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 0
Add a ment  | 

2 Answers 2

Reset to default 11

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);
    }
});

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