Skip to content

Instantly share code, notes, and snippets.

@evanhammer
Last active March 23, 2017 21:59
Show Gist options
  • Save evanhammer/39f996883e42560cdf8f68f59de05301 to your computer and use it in GitHub Desktop.
Save evanhammer/39f996883e42560cdf8f68f59de05301 to your computer and use it in GitHub Desktop.
Recursive Promise FileReader
const fs = require('fs');
const flatten = arrays => [].concat.apply([], arrays);
const isFile = err => err && err.code === 'ENOTDIR';
const getChildPaths = (dir, filenames) => filenames.map(f => dir + '/' + f);
const readFiles = (reader, path) => {
return new Promise((resolve, reject) => {
reader.readdir(path, (err, filenames) => {
resolve({ path, filenames, err });
});
})
.then(({ path, filenames, err }) => {
if (isFile(err)) {
return [path];
}
const paths = getChildPaths(path, filenames);
const promises = paths.map(p => readFiles(reader, p));
return Promise.all(promises).then(flatten);
});
};
readFiles(fs, '.').then(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment