UNPKG

@thi.ng/file-io

Version:

Assorted file I/O utils (with logging support) for NodeJS/Bun

42 lines (41 loc) 1.36 kB
import { readdirSync } from "node:fs"; import { sep } from "node:path"; import { isDirectory } from "./dir.js"; import { __ensurePred } from "./internal/ensure.js"; const files = (dir, match = "", maxDepth = Infinity, logger) => __files(dir, match, logger, maxDepth, 0); function* __files(dir, match = "", logger, maxDepth = Infinity, depth = 0) { if (depth >= maxDepth) return; const pred = __ensurePred(match); for (let f of readdirSync(dir).sort()) { const curr = dir + sep + f; try { if (isDirectory(curr)) { yield* __files(curr, match, logger, maxDepth, depth + 1); } else if (pred(curr)) { yield curr; } } catch (e) { logger && logger.warn(`ignoring file: ${f} (${e.message})`); } } } const dirs = (dir, match = "", maxDepth = Infinity, logger) => __dirs(dir, match, logger, maxDepth, 0); function* __dirs(dir, match = "", logger, maxDepth = Infinity, depth = 0) { if (depth >= maxDepth) return; const pred = __ensurePred(match); for (let f of readdirSync(dir).sort()) { const curr = dir + sep + f; try { if (isDirectory(curr)) { if (pred(curr)) yield curr; yield* __dirs(curr, match, logger, maxDepth, depth + 1); } } catch (e) { logger && logger.warn(`ignoring file/dir: ${f} (${e.message})`); } } } export { dirs, files };