我有搜索功能,一旦我有搜索字符串從clinet我想循環通過文件和匹配來自FS中的文件的字符串,我有循環中的問題我想獲得所有匹配結果並將結果發送到客戶端。下面試圖實現,但得到一個錯誤粘貼有問題。新的異步庫任何幫助將不勝感激。如何使用nodejs使用異步回調?
app.js
app.get('/serverSearch', function (req, res) {
var searchTxt = req.query.searchTxt;
dirDirectory.readDirectory(function(logFiles){
// res.json(logFiles);
if(logFiles){
searchFileService.readFile(searchTxt,logFiles,function(lines,err){
console.log('Logs',lines);
if (err)
return res.send();
res.json(lines);
})
}
});
console.log('Search text', searchTxt);
});
service.js
var fs = require('fs');
var path = require('path');
var async = require('async');
var searchStr;
var result = [];
//Async Method
function readFile(str, logFiles, callback) {
async.series([
//Load user to get `userId` first
function(callback) {
searchStr = str;
for (var i = 0; i < logFiles.length; i++) {
if (logFiles[i].filename !== '.gitignore') {
fs.readFile('logs/dit/' + logFiles[i].filename, 'utf8', function(err, data) {
if (err) {
return console.log(err);
}
inspectFile(data);
});
}
callback(result);
}
},
//Load posts (won't be called before task 1's "task callback" has been called)
function() {
function inspectFile(data, callback) {
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
result.push(line);
// then log it
return line;
}
});
}
}
], function(err) { //This function gets called after the two tasks have called their "task callbacks"
if (err) return err;
});
};
錯誤
if (fn === null) throw new Error("Callback was already called.");
有在你的代碼中的一些語法問題,我試圖解決 – hussain
啊對不起,我是混合ES6和ES5但它應該是接近你所需要的。希望能幫助到你! – djowinz
我是否必須從'readFile'功能以及 – hussain