Created
October 11, 2024 07:55
-
-
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
This file contains 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
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