-
-
Notifications
You must be signed in to change notification settings - Fork 0
5.3 find up
wiki[bot] edited this page Aug 23, 2026
·
1 revision
A utility function to recursively search for files by traversing up the directory tree.
import { findUp } from "@triplef/helpers/find-up";import { findUp } from "@triplef/helpers/find-up";
// Find package.json starting from current directory
const packagePath = findUp("package.json");
// Find README.md starting from a specific directory
const readmePath = findUp("README.md", "/path/to/start");
// Handle not found case
const configPath = findUp("config.json");
if (configPath) {
console.log(`Found config at ${configPath}`);
} else {
console.log("Config not found");
}function findUp(
filename: string,
startDir?: string
): string | nullParameters:
-
filename(string, required) - The name of the file to find (e.g., "package.json", "README.md") -
startDir(string, optional) - The directory to start searching from. Defaults toprocess.cwd()
Returns:
-
string- Absolute path to the found file -
null- If the file is not found up to the filesystem root
Behavior:
The function searches for the file starting from startDir and traverses up the directory tree until it either:
- Finds the file and returns its absolute path
- Reaches the filesystem root without finding the file and returns
null
If multiple files with the same name exist in different ancestor directories, the function returns the one closest to startDir.
// Look for a config file in the current project
const configPath = findUp("tsconfig.json");
if (configPath) {
const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
console.log("TypeScript configuration loaded");
}Used internally by readPackageJsonFromRoot:
import { findUp } from "@triplef/helpers/find-up";
import * as fs from "fs";
export function readPackageJsonFromRoot(
filename: string = "package.json",
startDir: string = process.cwd()
) {
const packagePath = findUp(filename, startDir);
if (!packagePath) throw Error(`File ${filename} not found`);
const fileContent = fs.readFileSync(packagePath, "utf8");
return JSON.parse(fileContent);
}// Start searching from a specific module's directory
const moduleDir = path.resolve(__dirname, "../..");
const rootPackage = findUp("package.json", moduleDir);-
Bootstrap - Uses
findUpinternally for readingpackage.json