{"id":13183,"library":"find-and-require-package-json","title":"Find and Require Package.json","description":"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.","status":"active","version":"0.9.1","language":"javascript","source_language":"en","source_url":"https://github.com/constructive-io/dev-utils","tags":["javascript","typescript"],"install":[{"cmd":"npm install find-and-require-package-json","lang":"bash","label":"npm"},{"cmd":"yarn add find-and-require-package-json","lang":"bash","label":"yarn"},{"cmd":"pnpm add find-and-require-package-json","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The module exports a named function. While CJS `require` might work with transpilers, direct ESM import is preferred.","wrong":"const findAndRequirePackageJson = require('find-and-require-package-json');","symbol":"findAndRequirePackageJson","correct":"import { findAndRequirePackageJson } from 'find-and-require-package-json';"},{"note":"Both async and sync versions are named exports from the main package entry point.","wrong":"import findAndRequirePackageJsonSync from 'find-and-require-package-json/sync';","symbol":"findAndRequirePackageJsonSync","correct":"import { findAndRequirePackageJsonSync } from 'find-and-require-package-json';"},{"note":"Import `PackageJson` as a type for type safety, as it's an interface.","wrong":"import { PackageJson } from 'find-and-require-package-json';","symbol":"PackageJson","correct":"import type { PackageJson } from 'find-and-require-package-json';"}],"quickstart":{"code":"import { findAndRequirePackageJson } from 'find-and-require-package-json';\nimport path from 'path';\nimport fs from 'fs';\n\nasync function runExample() {\n  // Create a dummy project structure for demonstration\n  const tempDir = path.join(__dirname, 'temp-project');\n  const subDir = path.join(tempDir, 'src', 'utils');\n  fs.mkdirSync(subDir, { recursive: true });\n\n  const dummyPackageJson = {\n    name: 'my-temp-app',\n    version: '1.0.0',\n    description: 'A temporary application',\n    dependencies: { 'lodash': '^4.17.21' }\n  };\n  fs.writeFileSync(path.join(tempDir, 'package.json'), JSON.stringify(dummyPackageJson, null, 2));\n\n  console.log('Searching for package.json starting from:', subDir);\n  try {\n    const { packageJson, filePath } = await findAndRequirePackageJson(subDir);\n    console.log('Found package.json at:', filePath);\n    console.log('Package Name:', packageJson.name);\n    console.log('Package Version:', packageJson.version);\n    console.log('Dependencies:', packageJson.dependencies);\n  } catch (error) {\n    console.error('Error finding package.json:', error.message);\n  } finally {\n    // Clean up dummy directory\n    fs.rmSync(tempDir, { recursive: true, force: true });\n  }\n}\n\nrunExample();","lang":"typescript","description":"Demonstrates how to use `findAndRequirePackageJson` asynchronously to locate and parse a `package.json` file from a nested directory, traversing upwards."},"warnings":[{"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.","message":"This 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.","severity":"gotcha","affected_versions":"<1.0.0"},{"fix":"Prefer the asynchronous `findAndRequirePackageJson` function for performance-critical paths, especially in server-side applications or long-running processes.","message":"The 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.","severity":"gotcha","affected_versions":">=0.1.0"},{"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.","message":"The 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.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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.","cause":"The `findAndRequirePackageJson` function could not locate a `package.json` file in the starting directory or by traversing up to the file system root.","error":"Error: package.json not found in <path> or any parent directory."},{"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; }`","cause":"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.","error":"TypeError: Cannot destructure property 'packageJson' of 'undefined' or 'null'."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}