Skip to content

Instantly share code, notes, and snippets.

@ugate
Last active June 3, 2020 13:51
Show Gist options
  • Save ugate/7fbaa5a3216ca8a388a868d07e3a26d6 to your computer and use it in GitHub Desktop.
Save ugate/7fbaa5a3216ca8a388a868d07e3a26d6 to your computer and use it in GitHub Desktop.
Recursively traverses a directory capturing all of the file paths in that directory and sub-directories yielding each path asynchronously
const Fs = require('fs');
const Path = require('path');
/**
* Generates a set of file paths by recursively traversing the given directory
* @param {String} dir The directory to traverse
* @param {Boolean} [join] Truthy to use `path.join` vs the _default_ concatination
* @yields {String} The next file path in the traversal
*/
async function* files(dir, join) {
for await (const sdir of await Fs.promises.opendir(dir)) {
const loc = join ? Path.join(dir, sdir.name) : `${dir}/${sdir.name}`;
if (sdir.isDirectory()) yield* files(loc);
else if (sdir.isFile()) yield loc;
}
}
// example run
const root = '/test';
for await (const path of files(root)) {
console.log(path);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment