Node.js 'not Found' Callback For Async.detect?
Solution 1:
from the documentation you mentioned.
in case of detect(arr, iterator, callback)
callback(result) - A callback which is called as soon as any iterator returns true, or after all the iterator functions have finished. Result will be the first item in the array that passes the truth test (iterator) or the value undefined if none passed.
from your question you want to find a way to detect if no file in list is found, which could be done by comparing the result
with undefined
and checking whether this condition is true.
like
async.detect(['file1','file2','file3'], fs.exists, function(result){
if(typeof(result)=="undefined") {
//none of the files where found so undefined
}
});
Solution 2:
I would use async.each and use fs.exists to detect if the file exists. If it exists, then read the file otherwise, call the not found function then proceed to the next item. See sample code I have written on top of my head below.
async.each(file_paths, processItem, function(err) {
if(err) {
console.log(err);
throw err;
return;
}
console.log('done reading file paths..');
});
function notFound(file_path) {
console.log(file_path + ' not found..');
}
function processItem(file_path, next) {
fs.exists(file_path, function(exists) {
if(exists) {
//file exists//do some processing//call next when done
fs.readFile(file_path, function (err, data) {
if (err) throw err;
//do what you want here//then call nextnext();
});
}
else {
//file does not existnotFound(file_path);
//proceed to next itemnext();
}
});
}
Post a Comment for "Node.js 'not Found' Callback For Async.detect?"