Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.