{"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,"search_vec":"'-1.0':69 '/package.json':103 '0.9.1':60 'alway':132 'break':75 'build':86 'chang':76 'cli':88 'compil':148 'compile-tim':147 'complex':122 'consid':63 'contain':133 'current':57,127 'depend':108 'desir':135 'develop':144 'directori':38,45,129 'discov':95 'dynam':94 'enhanc':143 'environ':92 'essenti':99 'experi':145 'file':30,49 'find':1,9 'find-and-require-package-json':8 'flexibl':113 'found':51 'full':140 'function':21 'futur':78 'ideal':118 'intellig':40 'introduc':73 'javascript':151 'json':13 'librari':110 'lie':84 'locat':24 'make':116 'may':72 'mechan':115 'metadata':97 'might':130 'minor':74,79 'modul':7 'monorepo':120 'offer':111 'oper':32 'packag':12 'package.json':4,29,48,136 'parent':44 'pars':27 'path':107 'path-depend':106 'pre':68 'primari':82 'programmat':23 'project':96,123 'provid':14 'reach':56 'read':25 'releas':70 'requir':3,11,102 'robust':16 'root':54 'runtim':91 'safe':20 'safeti':150 'search':114 'ship':138 'simpl':101 'specifi':37 'stabl':64 'start':34 'structur':124 'system':87 'time':149 'tool':89 'travers':41 'type':19,142 'type-saf':18 'typescript':6,141,152 'unlik':100 'upward':42 'util':83 'version':59,80 'work':128","created_at":"2026-04-20T01:53:10.992777+00:00","updated_at":"2026-04-20T01:53:10.992777+00:00","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,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/constructive-io/dev-utils","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/find-and-require-package-json","openapi_spec":null,"status_page":null,"smithery":null,"categories":["devops"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}