Skip to content

Instantly share code, notes, and snippets.

@rob-mccann
Last active August 29, 2015 14:17
Show Gist options
  • Save rob-mccann/0be14a5cad939ab9c854 to your computer and use it in GitHub Desktop.
Save rob-mccann/0be14a5cad939ab9c854 to your computer and use it in GitHub Desktop.
List files in a directory asynchronously using async generators in ES7.
/**
* My first foray into the land of ES7.
*
* We had an interesting challenge in our office of using node to output the files
* in a given directory and it's subdirectories and sort them.
*
* We had some very interesting solutions from using co-routines to
* pub/subs from an a wide variety of engineers from C developers to front-enders.
*
* Here's my solution using some ES7 features.
*
* You can run this in traceur but you'll need the experimental flag
* and a library to promisify node's fs lib. You'll need to polyfill Array.from
* which I haven't tested yet.
*/
async function* ls(path) {
let files = await fs.readdir(path);
for (let file of files) {
let subPath = `${path}/${file}`,
stat = await fs.lstat(subPath);
if (stat.isDirectory()) {
yield* ls(subPath);
} else {
yield subPath;
}
}
}
(async function() {
console.log(Array.from(ls(process.cwd())).sort().join("\n")); // untested, not supported yet, could polyfil
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment