[英]Node.js: When do you know when a collection of asynchronous tasks is done?
我想下降一個目錄,並針對正則表達式檢查在此看到的每個文件的名稱。 基本上,是通用unix find
命令的一個版本,僅用Node.js編寫。 我不在乎文件的順序,但是我想確保我能全部得到文件。
我有以下代碼,(我認為)與我想要的代碼很接近。 它需要一個startdir,一個regexp和一個回調。 對於每個文件,它都會對sentinel
的值加一,而在完成分析后,它將使哨兵的值減一。 我擔心的是,如果有一個文件和一個深度嵌套的目錄集合,它將分析該文件並在找到第二個文件之前很長一段時間觸發回調,並且可能會兩次調用該回調。
顯然,我可以通過使用fired
變量來阻止第二次觸發來防止兩次調用該回調。 但這仍然會給我錯誤的數據。 我在這里做錯了什么,還有一種更適合節點的方法嗎?
fs = require('fs')
path = require('path')
function get_all_files(startdir, regexp, callback) {
var sentinel = 0;
var results = [];
function check_sentinel() {
sentinel--;
if (sentinel === 0) {
callback(results);
}
}
function check_file(dir, filename) {
var fname;
sentinel++;
if (regexp.test(filename)) {
results.push(path.join(dir, filename));
}
check_sentinel();
}
function check_directory(dir) {
fs.readdir(path.join(this.rootpath, dirpath), function(err, files) {
var fname, i, len, npath;
if (err) {
throw err
}
for (i = 0, len = files.length; i < len; i++) {
fname = files[i];
npath = path.join(dir, fname);
fs.stat(npath, function(err, stats) {
if (stats.isFile()) {
check_file(dir, fname);
} else {
if (stats.isDirectory()) {
check_directory(npath);
}
}
});
}
});
}
check_directory(startdir);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.