Sunday, January 15, 2017

Listing all files recursively using bluebird promise

var Promise = require("bluebird");
var fs = Promise.promisifyAll(require('fs'));
var Path = require('path');
var dir = '/home/test_user/pictures/sample';


var ext = ['.txt', '.jpg'];
let files = [];

function walk(dir, ext) {
    return fs.readdirAsync(dir).map(function (fileName) {
        fileName = Path.join(dir, fileName);
        var extname = Path.extname(fileName);

        if ((ext.indexOf(extname) > -1) || (extname == '')) {
            return fs.statAsync(fileName)
                .then(function (stats) {
                    return stats.isDirectory() ? walk(fileName, ext) : fileName;
                })
        } else {
            return false
        }
    }).reduce(function (a, b) {
        if (b == false) {
            return a;
        } else {
            return a.concat(b);
        }
    }, []);
}

var res = walk(dir, ext).then(function (v) {
    console.log(JSON.stringify(v));
});

No comments:

Post a Comment