Skip to content

Instantly share code, notes, and snippets.

@splatterxl
Created August 9, 2023 15:46
Show Gist options
  • Save splatterxl/ba6991bd31fa53a9210a5ea9c6e749f9 to your computer and use it in GitHub Desktop.
Save splatterxl/ba6991bd31fa53a9210a5ea9c6e749f9 to your computer and use it in GitHub Desktop.
recursively walk and import directory in nodejs
import * as fs from "node:fs/promises";
export async function* walk<T>(
dir: string
): AsyncGenerator<[{ name: string; path: string }, T]> {
for (const file of await fs.readdir(dir)) {
const path = `${dir}/${file}`;
const stat = await fs.stat(path);
if (stat.isDirectory()) {
yield* await load<T>(path);
} else {
const name = file.replace(/\.js$/, "");
const data = await import(path);
yield [{ name, path }, data as T];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment