Created
March 20, 2023 03:36
-
-
Save zoxon/e3da1a5fc6c7035a87d287d445c91783 to your computer and use it in GitHub Desktop.
Nodejs walk dir example
This file contains hidden or 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 { readdir } from "node:fs/promises"; | |
import { extname, resolve } from "node:path"; | |
async function* walkDir(dir: string): AsyncGenerator<string> { | |
const entries = await readdir(dir, { withFileTypes: true }); | |
for (const entry of entries) { | |
const name = resolve(dir, entry.name); | |
if (entry.isDirectory()) { | |
yield* walkDir(name); | |
} else if (filterFile(entry.name)) { | |
yield name; | |
} | |
} | |
} | |
const filterFile = (file: string): boolean => { | |
return [".css", ".js", ".html", ".xml", ".cjs", ".mjs", ".svg", ".txt"].some( | |
(ext) => extname(file) == ext, | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment