Snippets

Glenn Gentzke edited this page Jun 24, 2015 · 7 revisions

This page will contain snippets and examples of common tasks done with promises.

###Reading directory and sub-directory contents recursively

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