List files in a directory asynchronously using async generators in ES7.
This file contains hidden or 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
| /** | |
| * 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 | |
| })(); |