20 lines
811 B
TypeScript
Raw Normal View History

import { readdir } from "fs/promises";
2023-04-06 21:34:20 +02:00
import { resolve, sep } from "path";
/**
* Asynchronously and recursively walk a directory tree, yielding every file and directory
2023-04-06 21:34:20 +02:00
* found. Directory paths will _always_ end with a path separator.
*
* @param root the starting directory
* @returns AsyncGenerator
*/
export default async function* walk(root: string): AsyncGenerator<string, void, unknown> {
for (const entry of await readdir(root, { withFileTypes: true })) {
const absolutePath = resolve(root, entry.name);
if (entry.isDirectory()) {
2023-04-06 21:34:20 +02:00
yield absolutePath.endsWith(sep) ? absolutePath : (absolutePath + sep);
yield* walk(absolutePath);
2023-04-06 21:34:20 +02:00
} else yield absolutePath.endsWith(sep) ? absolutePath.substring(0, absolutePath.length-1) : absolutePath;
}
}