-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Snippets
Julien Fontanet edited this page Jul 11, 2018
·
8 revisions
This page will contain snippets and examples of common tasks done with promises.
This example will read the input directory for its files and sub-directories recursively and returns a promise that will resolve to an array of all the files found.
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs"));
var Path = require("path");
function readDir(dirName) {
return fs.readdirAsync(dirName).map(function (fileName) {
var path = Path.join(dirName, fileName);
return fs.statAsync(path).then(function(stat) {
return stat.isDirectory() ? readDir(path) : path;
});
}).reduce(function (a, b) {
return a.concat(b);
}, []);
}
readDir("./mydir").then(function(v){
console.log(v.join("\n"));
});
With the directory structure:
/mydir
file1.txt
file2.txt
/deeper
depths.txt
/deeper2
/even_deeper
really_deep_file.txt
deep_file.txt
The example will print:
$ node snippet.js
mydir/deeper/depths.txt
mydir/deeper2/deep_file.txt
mydir/deeper2/even_deeper/really_deep_file.txt
mydir/file1.txt
mydir/file2.txt