Skip to content

Instantly share code, notes, and snippets.

@tylerpaige
Created January 3, 2019 19:05
Show Gist options
  • Save tylerpaige/cbc2ca5478444ce63167e7e920f60d9e to your computer and use it in GitHub Desktop.
Save tylerpaige/cbc2ca5478444ce63167e7e920f60d9e to your computer and use it in GitHub Desktop.
get an array of subfolders given a path
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