Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am aware of io-q, the library that does async IO resulting in promises. But I'm looking for a simple example of using the Q library to recursively traverse a directory structure, where the final result is a list of all the files in all the directories starting in the folder provided to some function, but flattened in the process to a single array of file names.

Is there an example of this out there? Or perhaps there's an example that isn't recursive, which is fine. I'm guessing this is pretty simple, but this is my first exposure to both async/promises.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
772 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...