vfile-find-up

7.1.0 · active · verified Sun Apr 19

vfile-find-up is a utility within the vfile ecosystem designed to locate one or more files by traversing the file system upwards from a specified path. It operates on `vfile` objects, which standardize virtual file representation, making it suitable for unified processing workflows. The current stable version is 7.1.0, and the package maintains a steady release cadence, typically introducing major versions for breaking API changes or significant architectural shifts. Key differentiators include its tight integration with `vfile` for consistent file handling, its specific focus on *upward* directory traversal (contrasting with `vfile-find-down`), and its provision of both promise-based and traditional callback APIs, offering flexibility for asynchronous operations. It's particularly useful for locating configuration files or project roots.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `findUp` to locate the first `package.json` and `findUpAll` with a custom test function to find all markdown files, along with reading file content using `to-vfile`.

import { findUp, findUpAll } from 'vfile-find-up';
import { toVFile } from 'to-vfile'; // Recommended for reading file content

async function runFindUpExamples() {
  const currentDir = process.cwd();

  // Find the first package.json upwards
  console.log('--- Finding single package.json ---');
  try {
    const pkgFile = await findUp('package.json', currentDir);
    if (pkgFile) {
      console.log(`Found package.json at: ${pkgFile.path}`);
      // To read its content, use to-vfile
      const fullPkgFile = await toVFile.read(pkgFile.path);
      console.log('Content (first 100 chars):', fullPkgFile.value?.toString().substring(0, 100) + '...');
    } else {
      console.log('No package.json found upwards.');
    }
  } catch (error) {
    console.error('Error finding package.json:', error);
  }

  // Find all .md files upwards (demonstrating custom test function)
  console.log('\n--- Finding all .md files upwards ---');
  try {
    const mdFiles = await findUpAll((file) => file.extname === '.md', currentDir);
    if (mdFiles.length > 0) {
      console.log(`Found ${mdFiles.length} markdown files:`);
      mdFiles.forEach((file) => console.log(`- ${file.path}`));
    } else {
      console.log('No markdown files found upwards.');
    }
  } catch (error) {
    console.error('Error finding markdown files:', error);
  }
}

runFindUpExamples();

view raw JSON →