Created
January 3, 2019 19:05
-
-
Save tylerpaige/cbc2ca5478444ce63167e7e920f60d9e to your computer and use it in GitHub Desktop.
get an array of subfolders given a path
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 { promisify } = require('util'); | |
const readFile = promisify(fs.readFile); | |
const lstat = promisify(fs.lstat); | |
const readDir = promisify(fs.readdir); | |
const isDirectory = source => { | |
return lstat(source).then(stats => | |
Promise.resolve(stats.isDirectory() ? source : false) | |
); | |
}; | |
const getDirectories = function getDirectories(source) { | |
return readDir(source).then(async children => { | |
const promises = children.map(name => | |
isDirectory(path.resolve(source, name)) | |
); | |
/* | |
Array.filter is synchronous, so we have to wait | |
for all lstat operations to finish before we can proceed | |
*/ | |
const results = await Promise.all(promises); | |
return results.filter(r => r); | |
}); | |
}; | |
const getDirectoriesRecursive = async function getDirectoriesRecursive(source) { | |
const dirs = await getDirectories(source); | |
return dirs.reduce(async (accPromise, cur) => { | |
/* | |
In async reductions, the accumulator is a promise, | |
so any easy workaround is to just await it. | |
*/ | |
const acc = await accPromise; | |
const subdirs = await getDirectoriesRecursive(cur); | |
return acc.concat(cur, subdirs); | |
}, []); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment