NodeJS - 给定目录的完整路径,如何获取所有子目录的列表并异步检查文件是否存在?

NodeJS - Given a full path of a directory, how to get a list of all subdirectories and check if a file exists here asynchronously?

例如给定:'/Users/John/Desktop/FooApp', 我想得到一个列表,例如:

['/Users/John/Desktop/FooApp',
 '/Users/John/Desktop/FooApp/Folder1',
 '/Users/John/Desktop/FooApp/Folder2',
 '/Users/John/Desktop/FooApp/Folder2/folderA',
 '/Users/John/Desktop/FooApp/Folder3',
 '/Users/John/Desktop/FooApp/Folder3/folderX',
 '/Users/John/Desktop/FooApp/Folder3/folderX/folderY',
 '/Users/John/Desktop/FooApp/Folder3/folderX/folderY/folderZ',
 '/Users/John/Desktop/FooApp/Folder3/folderX/folderY2'
]

我要求此列表搜索所有目录以检查文件是否存在。用户输入一个文件夹,我基本上会执行类似于 OS 中的查找器的检查。我打算检查所有子目录的 fs.exists(subdir + '/mylib.dll')。有什么巧妙的方法可以做到这一点吗?

我已将 here, where search was performed for files instead of directories. I also used async 中类似问题的答案转换为检查文件是否存在。我还发现 fs.exists 即将被弃用,因此决定继续使用 fs.open

无论如何,这是片段:

var fs = require('fs');

var getDirs = function(dir, cb){
    var dirs = [dir];
    fs.readdir(dir, function(err, list){
        if(err) return cb(err);
        var pending = list.length;
        if(!pending) return cb(null, dirs);

        list.forEach(function(subpath){
            var subdir = dir + '/' + subpath;
            fs.stat(subdir, function(err, stat){
                if(err) return cb(err);

                if(stat && stat.isDirectory()){
                    dirs.push(subdir);
                    getDirs(subdir, function(err, res){
                        dirs = dirs.concat(res);
                        if(!--pending) cb(null, dirs);
                    });
                } else {
                    if(!--pending) cb(null, dirs);
                }
            });
        });
    });
};

然后可以将其用作:

var async = require('async');

getDirs('/Users/John/Desktop/FooApp', function(err, list){
    if(err) return 'Error retrieving sub-directories';

    async.detect(list, function(dir, cb){
            fs.open(dir + '/mylib.dll', 'r', function(err, file){
                if(err) cb(false);
                else cb(true);
            });
        }, 
        function(dir) {
            if(!dir) return 'File Not Found';
            /* Do something with the found file ... */
        }
    );
});