This is my first time i am working with promises , So i have use bluebird
library to achieve my task, In below code i have string input from client that i have to search in fileSystem. So i have to loop through dir and check if that string matched with any file push that line to results
so once forEach
finish i want to send results
to client. How can i achieve that task using promises ? error with below code
Error: Unhandled rejection TypeError: expecting an array or an iterable object but got [object Null]
app.js
searchFileService.readFile(searchTxt, logFiles, function(lines, err) {
console.log('Logs', lines);
if (err)
return res.send();
res.json(lines);
})
promises.js
function readFile(str,logFiles,callback){
searchStr = str;
return Promise.map(logFiles, function(logfile) {
return new Promise(function(resolve, reject) {
fs.readFile('logs/dit/' + logfile.filename, 'utf8', function(err, data) {
if (err) {
callback(null,err);
return; // **** Make sure not to run the code below!
}
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(line);
}
});
});
})
});
//}
}
Promise
.all(readFile())
.then(function() {
console.log('done');
callback(results);
});