Skip to content

Instantly share code, notes, and snippets.

@ugate
Last active June 3, 2020 13:51
Show Gist options
  • Select an option

  • Save ugate/7fbaa5a3216ca8a388a868d07e3a26d6 to your computer and use it in GitHub Desktop.

Select an option

Save ugate/7fbaa5a3216ca8a388a868d07e3a26d6 to your computer and use it in GitHub Desktop.

Revisions

  1. ugate revised this gist Jun 3, 2020. No changes.
  2. ugate created this gist Jun 3, 2020.
    22 changes: 22 additions & 0 deletions recursive-file-paths-generator.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    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);
    }