Created
May 20, 2016 05:00
-
-
Save UziTech/a29cefc060fdae2079057a1ca65b8443 to your computer and use it in GitHub Desktop.
node get files from directory asynchronously and recursively with promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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