Skip to content

Instantly share code, notes, and snippets.

@UziTech
Created May 20, 2016 05:00
Show Gist options
  • Save UziTech/a29cefc060fdae2079057a1ca65b8443 to your computer and use it in GitHub Desktop.
Save UziTech/a29cefc060fdae2079057a1ca65b8443 to your computer and use it in GitHub Desktop.
node get files from directory asynchronously and recursively with promises
/*
* License: MIT
* Author: Tony Brix, https://Tony.Brix.ninja
* Description: Get files from directory asynchronously and recursively with promises.
*/
var fs = require("fs");
var path = require("path");
module.exports = {
getFiles: function (filePath) {
return new Promise((resolve) => {
fs.stat(filePath, (err, stats) => {
if (err) {
throw err;
}
if (stats.isFile()) {
resolve([filePath]);
} else {
fs.readdir(filePath, (err, files) => {
if (err) {
throw err;
}
Promise.all(files.map((file) => {
return this.getFiles(path.resolve(filePath, file));
}))
.then((files) => {
// files will be an array of arrays.
// We want to change it to a flat array.
resolve([].concat.apply([], files));
});
});
}
});
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment