@visulima/fs
Version:
Human friendly file system utilities for Node.js
66 lines (62 loc) • 2.31 kB
JavaScript
;
const promises = require('node:fs/promises');
const node_url = require('node:url');
const path = require('@visulima/path');
const utils = require('@visulima/path/utils');
const F_OK = require('./F_OK-CWSqQIdF.cjs');
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 ? utils.toPath(options.cwd) : process.cwd();
let directory = path.resolve(cwd);
const { root } = path.parse(directory);
const stopPath = utils.toPath(options.stopAt ?? root);
const stopAt = path.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 ? promises.stat : promises.lstat;
while (directory && directory !== stopAt && directory !== root) {
for await (let fileName of await getMatchers(directory)) {
if (fileName === F_OK.FIND_UP_STOP) {
return undefined;
}
if (fileName === undefined) {
continue;
}
if (Buffer.isBuffer(fileName)) {
fileName = fileName.toString();
} else if (fileName instanceof URL) {
fileName = node_url.fileURLToPath(fileName);
}
const filePath = path.isAbsolute(fileName) ? fileName : path.resolve(directory, fileName);
try {
const stats = await statFunction(filePath);
if (type === "file" && stats.isFile() || type === "directory" && stats.isDirectory()) {
return filePath;
}
} catch {
}
}
directory = path.dirname(directory);
}
return undefined;
}, "findUp");
module.exports = findUp;