Skip to content

Instantly share code, notes, and snippets.

@maxholman
Last active November 27, 2022 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxholman/80979ac8e36fbb40aba44d7115cbf600 to your computer and use it in GitHub Desktop.
Save maxholman/80979ac8e36fbb40aba44d7115cbf600 to your computer and use it in GitHub Desktop.
Recursive readdir typescript
import { readdir, stat } from 'node:fs/promises';
async function* recursiveReaddir(dir: URL): AsyncGenerator<URL> {
for await (const file of await readdir(dir)) {
const path = new URL(file, `${dir}/`);
const x = await stat(path);
if (x.isDirectory()) {
yield* recursiveReaddir(path);
} else {
yield path;
}
}
}
import { readdirSync, statSync } from 'fs';
import { join } from 'path';
function recursiveReaddir(dir: string): string[] {
const files = readdirSync(dir);
return files.flatMap((file) => {
const path = join(dir, file);
if (statSync(path).isDirectory()) {
return recursiveReaddirSync(path);
}
return path;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment