Skip to content

Instantly share code, notes, and snippets.

@MrOrz
Forked from tomchentw/walk.js
Last active August 29, 2015 14:15
Show Gist options
  • Save MrOrz/c616d73cf94b082aee6a to your computer and use it in GitHub Desktop.
Save MrOrz/c616d73cf94b082aee6a to your computer and use it in GitHub Desktop.
walkAsync now does not assume `path` is a directory now.
/*
Recursively traverses the given dir and returns a promise that resolves to
a list of files.
The promise is resolved only after all sub-directories being traversed.
*/
var walkAsync = function(path) {
return statAsync(path).then(function(stat){
if(stat.isDirectory()){
return readdirAsync(path).then(function(files){
return Promise.all(files.map(function(file){
return walkAsync(path + "/" + file);
}));
});
}else{
return Promise.resolve([path])
}
}).then(function(files){
return [].concat.apply([], files)
});
};
/* Utilities */
function readdirAsync(path){
var fs = fs || require('fs');
return new Promise(function(resolve, reject){
fs.readdir(path, function(err, files){
if(err) {reject(err);}
resolve(files);
});
});
}
function statAsync(path){
var fs = fs || require('fs');
return new Promise(function(resolve, reject){
fs.stat(path, function(err, stats){
if(err) {reject(err);}
resolve(stats);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment