2013-08-25 62 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