UNPKG

@augment-vir/node

Version:

A collection of augments, helpers types, functions, and classes only for Node.js (backend) JavaScript environments.

40 lines (39 loc) 1.63 kB
import { readdir, stat } from 'node:fs/promises'; import { join, relative } from 'node:path'; async function internalReadDirPathsRecursive(dirPath, basePath) { const dirContents = await readdir(dirPath); const recursiveContents = (await Promise.all(dirContents.map(async (fileName) => { const filePath = join(dirPath, fileName); if ((await stat(filePath)).isDirectory()) { return internalReadDirPathsRecursive(filePath, basePath); } else { return relative(basePath, filePath); } }))).flat(); return recursiveContents; } /** * Gets all files within a directory and its subdirectories, recursively. Returns an array of paths * relative to the given input path. * * @category Node : File * @category Package : @augment-vir/node * @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node) */ export async function readDirRecursive(dirPath) { return await internalReadDirPathsRecursive(dirPath, dirPath); } /** * Reads all files within a single directory and filters them by the given extension or extensions. * * @category Node : File * @category Package : @augment-vir/node * @returns That filtered list of paths. * @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node) */ export async function readDirFilesByExtension({ dirPath, extension, extensions, }) { const extensionsToCheck = extensions || [extension]; const fileNames = await readdir(dirPath); return fileNames.filter((fileName) => extensionsToCheck.some((extensionToCheck) => fileName.endsWith(extensionToCheck))); }