List files in a directory asynchronously using async generators in ES7.

1 min read Original article ↗

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
})();