escalade: Ascend Parent Directories

3.2.0 · active · verified Sun Apr 19

escalade is a minimalistic and performant utility designed for synchronously or asynchronously traversing up parent directories to locate a specific file or directory. It continuously executes a provided callback function for each directory in the ancestry chain until the callback returns a truthy value, at which point the absolute path to the found item is returned, or until the system root directory is reached. The current stable version is `3.2.0`, with releases occurring a few times a year for patches, minor features, and ecosystem compatibility updates (e.g., Deno support, TypeScript resolution fixes). Its primary differentiators are its extremely small footprint (183-210 bytes gzipped) and its clear separation into synchronous and asynchronous execution modes, catering to a wide range of Node.js and Deno environments. It strictly searches direct parent directories and does not explore sibling directories of parents.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use the async `escalade` function to traverse parent directories from a given starting path to find the nearest `package.json` file. It then logs the path and the package name if found.

import { join } from 'path';
import escalade from 'escalade';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = join(__filename, '..');

// Assuming a file structure like:
// project-root/
//   package.json
//   src/
//     index.js
//     features/
//       my-feature.js

const startPath = join(__dirname, 'features', 'my-feature.js');

console.log(`Starting search from: ${startPath}`);

async function findPackageJson() {
  const pkgPath = await escalade(startPath, (dir, names) => {
    console.log(`  Searching in: ${dir}`);
    if (names.includes('package.json')) {
      return 'package.json';
    }
  });

  if (pkgPath) {
    console.log(`Found package.json at: ${pkgPath}`);
    const packageJson = await import(pkgPath, { assert: { type: 'json' } });
    console.log(`Package name: ${packageJson.default.name}`);
  } else {
    console.log('package.json not found in parent directories.');
  }
}

findPackageJson().catch(console.error);

view raw JSON →