Created
August 9, 2023 15:46
-
-
Save splatterxl/ba6991bd31fa53a9210a5ea9c6e749f9 to your computer and use it in GitHub Desktop.
recursively walk and import directory in nodejs
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 "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