Skip to content

Instantly share code, notes, and snippets.

@mick-io
Created July 27, 2022 18:28
Show Gist options
  • Save mick-io/bbe11963838cb8a9ea20b23cabc6803b to your computer and use it in GitHub Desktop.
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
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