Skip to content

Instantly share code, notes, and snippets.

@eblocha
Created February 6, 2024 03:11
Show Gist options
  • Save eblocha/8f2e9f39ac1096506a14ef37f6c92e4e to your computer and use it in GitHub Desktop.
Save eblocha/8f2e9f39ac1096506a14ef37f6c92e4e to your computer and use it in GitHub Desktop.
Walk A Directory Recursively Using an Async Generator
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