Registry / devops / find-and-require-package-json

find-and-require-package-json

JSON →
library0.9.1jsnpmunverified

This TypeScript module, `find-and-require-package-json`, provides a robust and type-safe function to programmatically locate, read, and parse a `package.json` file. It operates by starting from a specified directory and intelligently traversing upwards through parent directories until a `package.json` file is found or the root is reached. Currently at version 0.9.1, it is considered stable but, as a pre-1.0 release, it may introduce minor breaking changes in future minor versions. Its primary utility lies in build systems, CLI tools, and runtime environments where dynamically discovering project metadata is essential. Unlike simple `require('./package.json')` which is path-dependent, this library offers a flexible search mechanism, making it ideal for monorepos or complex project structures where the current working directory might not always contain the desired `package.json`. It ships with full TypeScript types, enhancing developer experience and compile-time safety.

npm install find-and-require-package-json
INSTALL
IMPORT
SIG · FIND-AND-REQUIRE-P
F
find-and-require-package-json
devopsjavascriptv0.9.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

findAndRequirePackageJson
import { findAndRequirePackageJson } from 'find-and-require-package-json';
const findAndRequirePackageJson = require('find-and-require-package-json');
The module exports a named function. While CJS `require` might work with transpilers, direct ESM import is preferred.
findAndRequirePackageJsonSync
import { findAndRequirePackageJsonSync } from 'find-and-require-package-json';
import findAndRequirePackageJsonSync from 'find-and-require-package-json/sync';
Both async and sync versions are named exports from the main package entry point.
PackageJson
import type { PackageJson } from 'find-and-require-package-json';
import { PackageJson } from 'find-and-require-package-json';
Import `PackageJson` as a type for type safety, as it's an interface.

Demonstrates how to use `findAndRequirePackageJson` asynchronously to locate and parse a `package.json` file from a nested directory, traversing upwards.

import { findAndRequirePackageJson } from 'find-and-require-package-json'; import path from 'path'; import fs from 'fs'; async function runExample() { // Create a dummy project structure for demonstration const tempDir = path.join(__dirname, 'temp-project'); const subDir = path.join(tempDir, 'src', 'utils'); fs.mkdirSync(subDir, { recursive: true }); const dummyPackageJson = { name: 'my-temp-app', version: '1.0.0', description: 'A temporary application', dependencies: { 'lodash': '^4.17.21' } }; fs.writeFileSync(path.join(tempDir, 'package.json'), JSON.stringify(dummyPackageJson, null, 2)); console.log('Searching for package.json starting from:', subDir); try { const { packageJson, filePath } = await findAndRequirePackageJson(subDir); console.log('Found package.json at:', filePath); console.log('Package Name:', packageJson.name); console.log('Package Version:', packageJson.version); console.log('Dependencies:', packageJson.dependencies); } catch (error) { console.error('Error finding package.json:', error.message); } finally { // Clean up dummy directory fs.rmSync(tempDir, { recursive: true, force: true }); } } runExample();
Debug
Known issues
gotchaThis package is currently in a pre-1.0 state (v0.9.1). While considered stable, minor versions (e.g., 0.x.x to 0.y.z) may introduce breaking changes or API alterations without adhering strictly to semantic versioning guidelines.
fix
Always pin exact versions (`npm install find-and-require-package-json@0.9.1`) and review changelogs carefully when upgrading pre-1.0 versions.
affects: <1.0.0
gotchaThe synchronous function `findAndRequirePackageJsonSync` can block the Node.js event loop if the file system traversal is extensive or I/O is slow. It should be used cautiously, primarily in CLI tools or initialization scripts where blocking is acceptable.
fix
Prefer the asynchronous `findAndRequirePackageJson` function for performance-critical paths, especially in server-side applications or long-running processes.
affects: >=0.1.0
gotchaThe function will stop searching upwards when it reaches the root directory of the file system (or a drive letter on Windows). If `package.json` is not found within the search path, it will throw an error.
fix
Implement proper error handling (`try-catch`) when calling `findAndRequirePackageJson` or `findAndRequirePackageJsonSync` to gracefully manage scenarios where the file is not found. Consider providing a fallback `package.json` or logging a warning.
affects: >=0.1.0
Errors
Common errors & fixes
Error: package.json not found in <path> or any parent directory.
The `findAndRequirePackageJson` function could not locate a `package.json` file in the starting directory or by traversing up to the file system root.
fix
Verify that a `package.json` file exists in the expected location relative to the starting search path. Ensure the starting path provided to the function is correct.
TypeError: Cannot destructure property 'packageJson' of 'undefined' or 'null'.
The `findAndRequirePackageJson` or `findAndRequirePackageJsonSync` function returned `undefined` (or the promise resolved to `undefined`) because no `package.json` was found, and the return value was immediately destructured without a check.
fix
Always check if the result of the function call is valid before attempting to destructure it. For example: `const result = await findAndRequirePackageJson(startPath); if (result) { const { packageJson, filePath } = result; }`
Upgrade
Version history
0.9.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
4 hits · last 30 days
node
4
Resources
find-and-require-package-json — npm install find-and-require-package-json · libregistry