2013-08-25 63 views
0

我有一个文件路径列表file_paths,我想检测哪个文件存在。 如果有任何文件存在,我想阅读那个文件。否则,请调用另一个函数,例如 not_foundNode.js'未找到'async.detect回调?

我希望使用async.detect,但是当所有迭代器返回false时,我找不到添加'未找到'回调 的方法。

我试过这个,但没有工作。返回未定义,并没有输出。

async = require 'async' 

async.detect [1,2,3], (item, callback) -> 
    callback true if item == 4 
, (result) -> 
    console.log result ? result : 'Not Found' 

如果还有其他方法可以做,请将其添加到答案中。

+0

请包括您尝试过的代码块。 – mithunsatheesh

回答

1

from the documentation您提到。

detect(arr, iterator, callback)

回调(结果)的情况下 - 这是尽快任何迭代器称为 返回true,或者在所有的迭代器功能完成的回调。 结果将是数组中通过真值测试(迭代器)的第一项或未定义的值(如果没有通过)。

从你的问题,你想找到一种方法,如果在列表中没有文件被发现检测,这可能由resultundefined比较核对该条件是否为true来完成。

async.detect(['file1','file2','file3'], fs.exists, function(result){ 

    if(typeof(result)=="undefined") { 
     //none of the files where found so undefined 
    } 

}); 
+0

我已经试过这个,没有工作。 – Rix

+0

@Rix:什么是o/p?当你使用console.log(result)'时,你会得到什么?在提问中提供一些清晰度不是很好吗? – mithunsatheesh

+0

我正在使用异步0.2.9。 'async.detect [1,2,3],((i,c) - > c(true)if i == 4),(r) - > console.log r? r:'不'未定义返回,并且没有任何输出 – Rix

0

我会用async.each和使用fs.exists文件是否存在来检测。如果它存在,那么读取文件,否则调用未找到的函数,然后继续下一个项目。请参阅下面我写在头上的示例代码。

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 next 
     next(); 
     }); 

    } 
    else { 
     //file does not exist 
     notFound(file_path); 
     //proceed to next item 
     next(); 
    } 
    }); 
} 
+0

这不是我想要的。在所有迭代器返回“false”之后,我想只调用一次'not_found'函数。 – Rix