Read a package version from Node.js code
Read your package metadata with CommonJS or ESM, account for deployment paths, and inject the version at build time when appropriate.
For a CommonJS file beside package.json, read the version directly:
const packageInfo = require('./package.json');
console.log(packageInfo.version);
The relative path is resolved from the module containing require(), not from the shell's current directory. A module at src/utils/version.cjs may therefore need ../../package.json.
Read JSON from an ES module
On a Node release supporting JSON import attributes:
import pkg from './package.json' with { type: 'json' };
console.log(pkg.version);
Import attributes arrived in Node 18.20, 20.10, and 21.0. JSON modules and import attributes stopped being experimental in 18.20.5, 20.18.3, 22.12, and 23.1. Check the exact supported release rather than substituting the older assert syntax indiscriminately.
An explicit file read is another option and makes the location clear:
import { readFileSync } from 'node:fs';
const packageInfo = JSON.parse(
readFileSync(new URL('./package.json', import.meta.url), 'utf8')
);
console.log(packageInfo.version);
Both examples assume the metadata file is next to the executing module. CommonJS require() caches JSON; a manual file read reads it again whenever the code performs that operation.
Keep the version available after building
Bundling or moving files can invalidate source-relative paths. Either include the metadata at the expected runtime location or inject a version constant during the build. A multi-stage container that copies only dist may omit package.json entirely.
For esbuild, a POSIX-shell example is:
esbuild src/app.js --bundle --platform=node --define:APP_VERSION='"1.0.0"'
The application can then reference APP_VERSION. Supply the real package version from your build process; quoting differs between shells. TypeScript's resolveJsonModule enables typed JSON imports during compilation, but does not by itself satisfy Node's runtime loader rules or copy files into a deployment.
Within an npm script, npm exposes package metadata including npm_package_version. You can read it from process.env.npm_package_version. Do not assume it exists when launching the program directly with node.
Dependency versions and CLI output
Reading require('some-package/package.json').version works only if the package permits access to that subpath. An exports map can block it. Prefer a documented version API or use npm's dependency listing for diagnostics.
For a CLI, pass the known version to a command parser's version option, or handle --version explicitly and return before starting normal work. Decide whether the value should identify the source package, the deployed build, or both.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan