@thi.ng/file-io
Version:
Assorted file I/O utils (w/ logging support) for NodeJS/Bun
46 lines (45 loc) • 1.43 kB
JavaScript
import { readdirSync } from "node:fs";
import { sep } from "node:path";
import { isDirectory } from "./dir.js";
import { __ensurePred } from "./internal/ensure.js";
import { maskedPath } from "./mask.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) {
__error(logger, f, e);
}
}
}
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) {
__error(logger, f, e);
}
}
}
const __error = (logger, path, e) => logger?.warn(
`ignoring: ${maskedPath(path)} (${maskedPath(e.message)})`
);
export {
dirs,
files
};