2016-04-04 12 views
1

我正在爲一個特定字符串的實例搜索一個n-grams(大約100萬行)的大型外部文件,並且希望能夠從出現該字符串的文件中返回整行。想知道是否以及如何這可能。 這裏是我的時刻代碼:使用Node.js'fs.readFile()返回一個字符串出現的行

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「設計的一部分」。

任何幫助,這將不勝感激。

回答

2

一種選擇是使用正則表達式:由於有幾百萬行的你應該讀一行行不知何故像

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

謝謝你,這完美地工作我案件! – papahummle

0

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