Skip to content

Instantly share code, notes, and snippets.

@lukasholzer
Created September 6, 2018 08:27
Show Gist options
  • Save lukasholzer/85ddfd6ff2ba06624cdac1922aad6465 to your computer and use it in GitHub Desktop.
Save lukasholzer/85ddfd6ff2ba06624cdac1922aad6465 to your computer and use it in GitHub Desktop.
Util function for recursively reading a dir. In addition a RegEx can be passed to match on all the files.
import { readdir, stat } from 'fs';
import { join } from 'path';
import { promisify } from 'util';
const readdirAsync = promisify(readdir);
const statAsync = promisify(stat);
export async function readDirRecursively(
dir: string,
regex: RegExp = null,
allFiles: string[] = [],
): Promise<string[]> {
const files = (await readdirAsync(dir)).map(file => join(dir, file));
allFiles.push(...files);
await Promise.all(files.map(async file => (
(await statAsync(file)).isDirectory() && readDirRecursively(file, regex, allFiles)
)));
if (regex) {
return allFiles.filter(file => file.match(regex));
}
return allFiles;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment