getPackageJson
Resolve and read the nearest package.json by walking up the directory tree from a working directory.
Overview
getPackageJson is a utility for resolving and reading the nearest package.json file from a given working directory.
It walks up the directory tree starting from cwd (or process.cwd()) until a valid package.json is found, then returns the parsed result as a fully typed object.
- The function supports:
- Automatic nearest
package.jsondiscovery. - Custom starting directory via
cwd. - Node ESM and CommonJS environments.
- Monorepo and nested workspace structures.
- Typed results through
PackageJson.
- Automatic nearest
Why use this?
- Read package metadata without hardcoding file paths.
- Useful for build tools and bundler configuration.
- Works reliably in monorepos and nested packages.
- Avoids JSON module import limitations.
- Ideal for CLI tools and infrastructure scripts.
- Returns typed package metadata such as name, version, exports, and dependencies.
Importing
Syntax
Parameters
Prop
Type
options
Optional configuration object that defines how the utility function should behave in various scenarios, allowing customization and greater control at runtime.
cwd
-
Description:
Working directory of the target project.Behavior
- Determines where lookup for the nearest
package.jsonwill start. - Resolution walks upward through parent directories until a matching file is found.
- If provided, resolution begins from this directory.
- If omitted, defaults to
process.cwd().
Notes
- This should be the directory containing your project or workspace.
- Useful for monorepos, CLI tools, bundler configs, and infrastructure scripts.
- Results are not cached by default.
- Designed for infrastructure-level usage, not hot paths.
- Determines where lookup for the nearest
-
Required:
-
Type:
string -
Default:
process.cwd() -
Example:
TypeScript/JavaScript
Throws
- Throws if no
package.jsoncan be found. - Throws if the located
package.jsoncontains invalid JSON.
Returns
Returns a Promise<PackageJson>.
PackageJson represents the parsed contents of a package.json file as a structured object containing package metadata.
Common fields may include:
name.version.description.license.author.type.main.module.exports.scripts.dependencies.devDependencies.peerDependencies.
Throws
Throws a built-in JavaScript error in the following cases:
- No
package.jsonfile can be found while walking up the directory tree. - The located
package.jsoncontains invalid JSON and cannot be parsed. - The resolved
package.jsoncannot be read due to file system access issues.
Version information
- Since:
v0.0.7. - Category:
get. - Stability: ✅
Stable(Production-ready).
