Created
July 27, 2022 18:28
-
-
Save mick-io/bbe11963838cb8a9ea20b23cabc6803b to your computer and use it in GitHub Desktop.
Utility function for recursively resolving the absolute path of each file with in a directory and it's subdirectories
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 fs from 'fs'; | |
import path from 'path'; | |
/** | |
* resolveFilePaths returns the absolute paths of files contained with a | |
* directory and it's sub directories. | |
* @param dirPath the parent path | |
* @returns The absolute paths of the files | |
*/ | |
export async function resolveFilePaths(dirPath: string): Promise<string[]> { | |
const parentDir = path.resolve(dirPath); | |
const fileNames = await fs.promises.readdir(parentDir); | |
const filePaths = fileNames.map((fname) => path.join(parentDir, fname)); | |
const stats = await Promise.all(filePaths.map((p) => fs.promises.stat(p))); | |
const resolvedPaths: string[] = []; | |
const subDirPromises: Promise<string[]>[] = []; | |
for (let i = 0, len = filePaths.length; i < len; i++) { | |
stats[i].isDirectory() | |
? subDirPromises.push(resolveFilePaths(filePaths[i])) | |
: resolvedPaths.push(filePaths[i]); | |
} | |
const subDirFpaths = await Promise.all(subDirPromises); | |
return resolvedPaths.concat(...subDirFpaths); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment