使用Node.js的fs.readFile()返回出现string的行

我正在寻找一个n-grams(大约一百万行)的大外部文件来处理特定string的实例,并希望能够从出现该string的文件中返回整行。 想知道如果和如何这可能是可能的。 这是我的代码:

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包含一些很好的string,但是我需要能够得到它所属的n-gram。 例如,search“devise”会从文件中返回n-gram“devise的一部分”。

任何帮助,将不胜感激。

一种select是使用正则expression式:

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