Skip to content

Instantly share code, notes, and snippets.

@zirkelc
Created October 11, 2024 07:55
Show Gist options
  • Save zirkelc/556729d1f0eac1c95d4bcc6f0aab2c3c to your computer and use it in GitHub Desktop.
Save zirkelc/556729d1f0eac1c95d4bcc6f0aab2c3c to your computer and use it in GitHub Desktop.
Recursive generator function to list all files in a directory in Node.js
import fs from 'node:fs/promises';
import path from 'node:path';
async function* readAllFiles(dir: string): AsyncGenerator<string> {
// use fs.readdirSync() to avoid async
const files = await fs.readdir(dir, { withFileTypes: true });
for (const file of files) {
if (file.isDirectory()) {
yield* readAllFiles(path.join(dir, file.name));
} else {
yield path.join(dir, file.name);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment