【发布时间】:2017-03-01 21:26:01
【问题描述】:
在我的实现中,如果用户从客户端搜索,我想检查字符串是否是文件的一部分。我将该行数据作为响应发送回客户端。
我的问题是假设用户想要搜索testid012。因此,使用我当前的代码,它只能找到包含搜索字符串的单数行。相反,我想发送包含搜索字符串的多行响应,在本例中为testid012。这可行吗?
searchService.js
fs.readFile('logs/dit/' + logfile.filename, 'utf8', function (err, data) {
if (err) {
return done(err);
}
var lines = data.split('\n'); // get the lines
lines.forEach(function(line) { // for each line in lines
if (line.indexOf(searchStr) != -1) { // if the line contain the searchSt
results.push({
filename:logfile.filename,
value:line
});
}
});
// when you are done reading the file
done();
});
dit/server.log
testid012 Lorem test Ipsum is simply dummy text text of the printing and typesetting industrytestid Lorem test Ipsum is simply dummy text text of the printing and typesetting industrytestid Lorem test Ipsum is simply dummy text text of the printing and typesetting industry
Lorem test Ipsum is simply dummy text text of the printing and typesetting industry,testid Lorem test Ipsum is simply dummy text text of the printing and typesetting industry
testid013 Lorem test Ipsum is simply dummy text text of the printing and typesetting industry,testid Lorem test Ipsum is simply dummy text text of the printing and typesetting industrytestid Lorem test Ipsum is simply dummy text text of the printing and typesetting industry
Lorem test Ipsum is simply dummy text text of the printing and typesetting industry
【问题讨论】:
-
它是可行的,但我强烈建议不要这样做,我建议您在 Solr 中索引您的文件,并在 Solr 中查询此类搜索词,或者,至少如果您没有Solr,在您拥有的任何数据库中使用它,这也是我不推荐的,但至少不是您这样做的文件搜索方式。
-
我不能使用数据库来满足这个要求,我必须进行文件搜索。任何好的例子,我如何使用 FS 来实现。
标签: javascript node.js for-loop fs