使用Node.js'fs.readFile()返回字符串出现的行

Use Node.js' fs.readFile() to return the line in which a string appears

本文关键字:字符串 返回 readFile js Node fs 使用      更新时间:2024-01-01

我正在一个n-gram(约100万行)的大型外部文件中搜索特定字符串的实例,并希望能够返回该字符串出现的文件中的整行。想知道这是否可能以及如何可能。这是我目前的代码:

 composeLines = function(importantWords, cb) {
    var word = importantWords.shift();
    fs.readFile("./w5_.txt", function(err, cont) {
      if (err) throw err;
      console.log("String"+(cont.indexOf(word)>-1 ? " " : " not ")+"found");
      cb(importantWords);
    });
  };

有了这个代码,我可以确定文件w5_.txt是否包含一些字符串,这很好,但我需要能够获得它所属的n-gram。例如,搜索"设计"会从文件中返回n-gram"设计的一部分"。

如有任何帮助,我们将不胜感激。

一个选项是使用正则表达式:

// Make sure `word` is properly escaped first
// 'm' allows '^' and '$' to match line boundaries or
// start and beginning of the input (respectively)
var re = new RegExp('^.*' + word + '.*$', 'm');
var m = re.exec(cont);
if (m)
  console.log('Word %j found on line: %j', word, m[0]);
else
  console.log('Word %j not found', word);

由于有数百万行,您应该以某种方式逐行读取:

var word = importantWords.shift();
var matchCount = 0;
var lineCount  = 0;
var lineReader = require('readline').createInterface({
  input: require('fs').createReadStream('file.in')
});
lineReader.on('line', function (line) {
  lineCount++;
  if(-1 < line.indexOf(word)){
    console.log(line);
    matchCount++;
  }
});