【问题标题】:Returning the line of a searched text from a file using node.js使用 node.js 从文件中返回搜索文本的行
【发布时间】:2019-05-24 05:04:28
【问题描述】:

我正在使用 fs 读取文件的内容,然后在该文件中搜索特定的单词,如果文件包含该单词而不是返回布尔值或单词,我希望输出包含关键字的行.如何输出整行?

const fs = require("fs");
let file = fs.readFileSync("read.txt", "utf8");
if(file.indexOf("keyword") >= 0) {
    console.log("Line of the keyword");
}

如果该行包含关键字,我只希望 console.log() 输出该行。

【问题讨论】:

    标签: javascript node.js fs


    【解决方案1】:

    让我们首先尝试用新行从文件中拆分字符串。然后可以在结果数组中搜索关键字的出现。如果搜索成功,则打印与行号相同的数组索引。

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

    【讨论】:

      【解决方案2】:

      我知道您只是想注销您的结果,但看到另一种方法可能会很有趣,其中包括写入文件以及使用旨在逐行读取文件的包。将来可能会有所帮助。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-03
        • 2019-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        相关资源
        最近更新 更多