UNPKG

@augment-vir/node

Version:

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

41 lines (40 loc) 1.39 kB
import { awaitedForEach } from '@augment-vir/common'; import { join } from 'node:path'; /** * Walks files within a directory. * * @category Node : File * @category Package : @augment-vir/node * @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node) */ export async function walkFiles({ handleFileContents, shouldRead, startDirPath, fs, }) { const { readFile, readdir } = { /* node:coverage ignore next 2: dynamic imports are not branches. */ readFile: fs?.readFile || (await import('node:fs/promises')).readFile, readdir: fs?.readdir || (await import('node:fs/promises')).readdir, }; const children = await readdir(startDirPath, { withFileTypes: true, }); await awaitedForEach(children, async (file) => { const childPath = join(startDirPath, file.name); const isDir = file.isDirectory(); const willRead = shouldRead ? await shouldRead({ path: childPath, isDir }) : true; if (!willRead) { return; } if (isDir) { await walkFiles({ startDirPath: childPath, shouldRead, handleFileContents, }); } else { await handleFileContents({ path: childPath, contents: await readFile(childPath), }); } }); }