如何使用nodejs在文件中搜索多个关键字?

时间:2017-06-07 19:46:30

标签: javascript arrays node.js fs

假设我有来自客户端searchStr的多个搜索关键字应与文件中的行匹配,我将如何将text与文件中的每一行匹配,并将该行推送到{{1 }}。使用下面的代码我得到results的空响应,不知道实现了什么错误?

search.js

results

2 个答案:

答案 0 :(得分:0)

您的问题没有清楚地显示results发生的情况,但此代码应该返回results的某些值而没有任何依赖:

function asyncFiles(filesData) { async.eachSeries(filesData.logFiles, function(logfile, done) { // read file readStream = fs.createReadStream('./logs/' + filesData.searchEnv + '/' + logfile.filename, 'utf8') readStream.pipe(split()) .on('data', function(line) { var searchStr = [{"text":"4588769"},{"text":"request"}] searchStr.forEach(function(text) { if (line.toLowerCase().indexOf(text.toLowerCase()) != -1) var messageDateInfo = line.split('|')[0].replace(/[\[\]']+/g, ''); messageDateInfo = new Date(messageDateInfo).getTime(); searchStartDate = new Date(searchStartDate).getTime(); searchEndDate = new Date(searchEndDate).getTime(); if (messageDateInfo - searchStartDate > 0 && searchEndDate - messageDateInfo > 0) { results.push({ filename: logfile.filename, value: line }); } }); }); done(); }, function(err) { if (err) { console.log('error', err); } readStream.on('end', function() { setTimeout(function(){callback(results);},2000) }); //results = []; }); }

答案 1 :(得分:0)

您可以将慢速函数与任意逻辑混合,并通过同步JS执行程序nsynjs按顺序执行。您的代码将转换如下:

function process(textFile,filesData) {
    var results=[];
    for(var i=0; i<filesData.logFiles.length, i++ ) {
        var file = filesData.logFiles[i];
        var fh = new textFile();
        fh.open(file);
        var line;
        var searchStr = [{"text":"4588769"},{"text":"request"}]
        while (typeof(line = fh.readLine(nsynjsCtx).data) != 'undefined') {
            for(var i=0; i<searchStr.length; i++)
                if (line.toLowerCase().indexOf(searchStr[i].toLowerCase()) != -1) {
                    var messageDateInfo = line.split('|')[0].replace(new RegExp("[\[\]']+","g"), '');
                    messageDateInfo = new Date(messageDateInfo).getTime();
                    searchStartDate = new Date(searchStartDate).getTime();
                    searchEndDate = new Date(searchEndDate).getTime();
                    if (messageDateInfo - searchStartDate > 0 && searchEndDate - messageDateInfo > 0) {
                        results.push({
                            filename: logfile.filename,
                            value: line
                        });
                    };              
                };
        };
        fh.close();
    };
    return results;
};

你可以通过这样的nsynjs运行它:

var nsynjs = require('nsynjs');
var textFile = require('../../wrappers/nodeReadline').textFile; // part of nsynjs package

function process(...){
...
}

nsynjs.run(process,{},textFile,filesData,function (results) {
    console.log('done', results); // results are ready here
});