Created
September 6, 2018 08:27
-
-
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.
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 { 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