我想获取包含在目录中的唯一文件名列表,包括使用节点的子目录,并且在组合每个回调的结果时遇到了一些麻烦。我想避免重复操作,如果我只是从fs.stat
回调中记录文件名,就会发生这种情况。
var distinct = {};
function getNames(root) {
fs.readdir(root, function(err, list) {
list.forEach(function(file) {
file = root + '/' + file;
fs.stat(file, function(err, stat) {
if (!err && stat.isDirectory()) {
getNames(file);
} else {
distinct[path.basename(file)] = true;
}
});
});
});
}
// perform various operations on unique filename list
console.log(Object.keys(distinct));
当然,这console.log()
太早地调用了该函数并给出了不希望的结果。我怎样才能获得一组文件名来处理;有没有一种使用异步方法的好方法,即不必使用readdirSync
and statSync
?