Created
February 6, 2024 03:11
-
-
Save eblocha/8f2e9f39ac1096506a14ef37f6c92e4e to your computer and use it in GitHub Desktop.
Walk A Directory Recursively Using an Async Generator
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 * as fs from "fs/promises"; | |
import * as path from "path"; | |
export async function exists(path: string): Promise<boolean> { | |
return fs | |
.access(path, fs.constants.F_OK) | |
.then(() => true) | |
.catch(() => false); | |
} | |
export async function* walkFilesRecursively( | |
p: string | |
): AsyncGenerator<string, void, void> { | |
if (!(await exists(p))) return; | |
const stats = await fs.stat(p); | |
if (stats.isDirectory()) { | |
for (const dirent of await fs.readdir(p, { withFileTypes: true })) { | |
for await (const result of walkFilesRecursively( | |
path.join(dirent.path, dirent.name) | |
)) { | |
yield result; | |
} | |
} | |
} else if (stats.isFile()) { | |
yield p; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment