Skip to content

Instantly share code, notes, and snippets.

@bn-l
Created May 9, 2024 09:54
Show Gist options
  • Save bn-l/5ac4a18202090977c0b84755b2b885c6 to your computer and use it in GitHub Desktop.
Save bn-l/5ac4a18202090977c0b84755b2b885c6 to your computer and use it in GitHub Desktop.
Very cool snippet showing the use of a JS generator to walk a directory recursively. Yields the path of files found.
/**
* @param {string} rootPath
* @returns {Generator<string>}
*/
function* walk(rootPath) {
for (const entry of fs.readdirSync(rootPath, { withFileTypes: true })) {
const filePath = path.join(rootPath, entry.name);
if (entry.isDirectory()) yield* walk(filePath);
else yield filePath;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment