Skip to content

Instantly share code, notes, and snippets.

@zoxon
Created March 20, 2023 03:36
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 zoxon/e3da1a5fc6c7035a87d287d445c91783 to your computer and use it in GitHub Desktop.
Save zoxon/e3da1a5fc6c7035a87d287d445c91783 to your computer and use it in GitHub Desktop.
Nodejs walk dir example
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