I found this gist which does what you want and is easy to promisify:
var Q = require('q'),
fs = require('fs'),
p = require('path');
function readDir(path) {
return Q.nfcall(fs.lstat, path).then(function(stat) {
if (stat.isDirectory()) {
return Q.nfcall(fs.readdir, path).then(function(files) {
return Q.all(files
// .map(p.join.bind(p, path)).map(readDir)
.map(function(file) {
return readDir(p.join(path, file));
})
).then(
// Function.apply.bind(Array.prototype.concat, [])
function(results) {
return [].concat.apply([], results);
});
});
} else {
return [path];
}
});
}
It uses nfcall
to get promises for the filesystem API and Q.all
to wait for all subdirectory results before concatenating them.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…