Skip to content

5.3 find up

wiki[bot] edited this page Aug 23, 2026 · 1 revision

Find Up

A utility function to recursively search for files by traversing up the directory tree.

Installation

import { findUp } from "@triplef/helpers/find-up";

Usage

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");
}

API

findUp

function findUp(
  filename: string,
  startDir?: string
): string | null

Parameters:

  • 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 to process.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.

Examples

Finding Configuration Files

// 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");
}

Reading Package Information

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);
}

Searching from a Custom Directory

// Start searching from a specific module's directory
const moduleDir = path.resolve(__dirname, "../..");
const rootPackage = findUp("package.json", moduleDir);

Related

  • Bootstrap - Uses findUp internally for reading package.json

Clone this wiki locally