Skip to content

Instantly share code, notes, and snippets.

@abelaska
Created November 12, 2021 18:41
Show Gist options
  • Save abelaska/4d586464bbff263655ae50058f5c4562 to your computer and use it in GitHub Desktop.
Save abelaska/4d586464bbff263655ae50058f5c4562 to your computer and use it in GitHub Desktop.
async function* walkDirs(dir, opts) {
const files = [];
for await (const d of await fs.promises.opendir(dir)) {
const entry = path.join(dir, d.name);
if (d.isDirectory()) {
const exclude = opts?.excludes?.find((exc) =>
exc.startsWith('/') ? entry.startsWith(exc) : entry.endsWith(exc)
);
if (!exclude) {
yield* await walkDirs(entry, opts);
}
} else if (d.isFile()) {
const include = opts?.includes?.find((inc) =>
inc.startsWith('/') ? entry.startsWith(inc) : entry.endsWith(inc)
);
if (include) {
files.push(entry);
}
}
}
if (files.length) {
yield { dir, files };
}
}
const includes = ['.ts'];
const excludes = ['.git', '.vscode'];
for await (const { dir, files } of walkDirs(rootDir, { excludes, includes })) {
console.log(dir, files);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment