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-jsonVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to use `findAndRequirePackageJson` asynchronously to locate and parse a `package.json` file from a nested directory, traversing upwards.
Always pin exact versions (`npm install find-and-require-package-json@0.9.1`) and review changelogs carefully when upgrading pre-1.0 versions.
Prefer the asynchronous `findAndRequirePackageJson` function for performance-critical paths, especially in server-side applications or long-running processes.
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.
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.
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; }`No dependency data recorded yet.