UNPKG

@visulima/fs

Version:

Human friendly file system utilities for Node.js

64 lines (61 loc) 2.27 kB
import { stat, lstat } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; import { resolve, parse, isAbsolute, dirname } from '@visulima/path'; import { toPath } from '@visulima/path/utils'; import { FIND_UP_STOP } from './F_OK-JER1LjUr.mjs'; var __defProp = Object.defineProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); const findUp = /* @__PURE__ */ __name(async (name, options = {}) => { if (typeof name !== "string" && !Array.isArray(name) && typeof name !== "function") { throw new TypeError("The `name` argument must be of type `string` or `string[]`"); } const cwd = options.cwd ? toPath(options.cwd) : process.cwd(); let directory = resolve(cwd); const { root } = parse(directory); const stopPath = toPath(options.stopAt ?? root); const stopAt = resolve(directory, stopPath); const type = options.type ?? "file"; const getMatchers = /* @__PURE__ */ __name(async function(currentDirectory) { if (typeof name === "function") { const match = await name(currentDirectory); return [match]; } if (typeof name === "string") { return [name]; } if (Array.isArray(name)) { return name; } return [name]; }, "getMatchers"); if (options.allowSymlinks === undefined) { options.allowSymlinks = true; } const statFunction = options.allowSymlinks ? stat : lstat; while (directory && directory !== stopAt && directory !== root) { for await (let fileName of await getMatchers(directory)) { if (fileName === FIND_UP_STOP) { return undefined; } if (fileName === undefined) { continue; } if (Buffer.isBuffer(fileName)) { fileName = fileName.toString(); } else if (fileName instanceof URL) { fileName = fileURLToPath(fileName); } const filePath = isAbsolute(fileName) ? fileName : resolve(directory, fileName); try { const stats = await statFunction(filePath); if (type === "file" && stats.isFile() || type === "directory" && stats.isDirectory()) { return filePath; } } catch { } } directory = dirname(directory); } return undefined; }, "findUp"); export { findUp as default };