Skip to content

Instantly share code, notes, and snippets.

@tomfa
Last active July 20, 2023 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomfa/e1d4ca6f056e2b163aaad6af9fd00ae6 to your computer and use it in GitHub Desktop.
Save tomfa/e1d4ca6f056e2b163aaad6af9fd00ae6 to your computer and use it in GitHub Desktop.
TypeScript: fs.readDir recursive implementation
/*
* Walks a directory (fs.readdir but recursively)
* Context:
* - fs does not have support for walk/readdir recursively
* - fs-extra moved "walk" functionality to https://github.com/jprichardson/node-klaw
*/
export const listDirectory = async (
currentPath: string,
includeDirectories = false,
ignorePaths: Array<string> = ['.DS_Store'],
): Promise<string[]> => {
const dirsAndFiles = fs
.readdirSync(currentPath)
.filter((f) => !ignorePaths.includes(f));
const directories = dirsAndFiles.filter((f) =>
fs.lstatSync(path.join(currentPath, f)).isDirectory(),
);
const result = dirsAndFiles
.filter((f) => includeDirectories || !directories.includes(f))
.map((f) => path.join(currentPath, f));
const subResults = await Promise.all(
directories.map(async (dir) => {
const joinedPath = path.join(currentPath, dir);
return listDirectory(joinedPath, includeDirectories);
}),
);
result.push(...subResults.flatMap((s) => s));
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment