UNPKG

@visulima/fs

Version:

Human friendly file system utilities for Node.js

86 lines (79 loc) 2.96 kB
import { createRequire as __cjs_createRequire } from "node:module"; const __cjs_require = __cjs_createRequire(import.meta.url); const __cjs_getProcess = typeof globalThis !== "undefined" && typeof globalThis.process !== "undefined" ? globalThis.process : process; const __cjs_getBuiltinModule = (module) => { // Check if we're in Node.js and version supports getBuiltinModule if (typeof __cjs_getProcess !== "undefined" && __cjs_getProcess.versions && __cjs_getProcess.versions.node) { const [major, minor] = __cjs_getProcess.versions.node.split(".").map(Number); // Node.js 20.16.0+ and 22.3.0+ if (major > 22 || (major === 22 && minor >= 3) || (major === 20 && minor >= 16)) { return __cjs_getProcess.getBuiltinModule(module); } } // Fallback to createRequire return __cjs_require(module); }; const { stat, lstat } = __cjs_getBuiltinModule("node:fs/promises"); const { fileURLToPath } = __cjs_getBuiltinModule("node:url"); import { resolve, parse, isAbsolute, dirname } from '@visulima/path'; import { toPath } from '@visulima/path/utils'; import { FIND_UP_STOP } from './F_OK-BalxCn9n.js'; const findUp = 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 = 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]; }; if (options.allowSymlinks === void 0) { 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 void 0; } if (fileName === void 0) { 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 void 0; }; export { findUp as default };