Last active
March 23, 2017 21:59
-
-
Save evanhammer/39f996883e42560cdf8f68f59de05301 to your computer and use it in GitHub Desktop.
Recursive Promise FileReader
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
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