921

Is there a way to get the version set in the package.json file in a Node.js application? I would want something like this

var port = process.env.PORT || 3000
app.listen port
console.log "Express server listening on port %d in %s mode %s", app.address().port, app.settings.env, app.VERSION
2
  • 2
    Is it more important to get the version of Node or the version declared in package.json? If the form, this will give you the running version: console.log(process.version) Apr 28, 2018 at 16:32
  • Yes, you can easily get the version from the package.json file in Node.js code. Here's how you can do it: const version= require('./package.json').version; Mar 11 at 13:33

34 Answers 34

1281

I found that the following code fragment worked best for me. Since it uses require to load the package.json, it works regardless of the current working directory.

var pjson = require('./package.json');
console.log(pjson.version);

A warning, courtesy of @Pathogen:

Doing this with Browserify has security implications.
Be careful not to expose your package.json to the client, as it means that all your dependency version numbers, build and test commands and more are sent to the client.
If you're building server and client in the same project, you expose your server-side version numbers too. Such specific data can be used by an attacker to better fit the attack on your server.

17
  • 40
    if you keep getting burned by trying to grab this from different places (as I was), you can do require('root-require')('package.json').version Jan 13, 2014 at 2:40
  • 11
    Not working for my script with shebang installed globally. Error: Cannot find module 'package.json'.
    – exebook
    May 21, 2015 at 11:39
  • 21
    shorter - require('./package').version Jul 15, 2015 at 7:09
  • 86
    Warning! Doing this with browserify has security implications: package.json in your bundle means that all your dependency version numbers, build and test commands and more are sent to the client. If you're building server and client in the same project, you expose your serverside version numbers too.
    – Pathogen
    Nov 19, 2015 at 23:03
  • 13
    @Pathogen genversion solves the issue on client side. It's a tool that reads the version from package.json and generates an importable module from it. Disclaimer: I'm a maintainer. Oct 2, 2017 at 22:41
729

If your application is launched with npm start, you can simply use:

process.env.npm_package_version

See package.json vars for more details.

19
  • 23
    this is probably the best answer since most of the information in package.json is attached to the process runtime variable Jun 19, 2015 at 19:51
  • 8
    Yeap, I'm agree. This should be the right answer, using the process variable you don't need to open and read again the package.json file.
    – Juanma
    Aug 3, 2015 at 16:29
  • 23
    And outside of node (e.g., shell scripts executed via npm run …) the version will be in the environment variable $npm_package_version. Sep 11, 2015 at 19:13
  • 27
    When called from scripts of another package, this incorrectly reports the version of the calling package and not the called package.
    – jjrv
    Feb 6, 2016 at 5:58
  • 19
    It works within an electron app started with npm start, but not within a built electron app: for that, you can find it in app.getVersion.
    – ChrisV
    Oct 9, 2016 at 21:38
284

Using ES6 modules, you can do the following:

import {version} from './package.json';
13
  • 5
    I thought these were not supported in node: github.com/nodejs/help/issues/53
    – ripper234
    Feb 26, 2017 at 19:24
  • 3
    No es6 modules are not yet directly supported but commonly used anyway, enabled using Babel Feb 27, 2017 at 14:52
  • 12
    @Sornii no, the entire package.json will be in the client. I used webpack's definePlugin to pass only selected info from node environment to browser.
    – doeke
    Oct 13, 2017 at 9:58
  • 7
    Any security implication like as specified in stackoverflow.com/a/10855054/540144 ?
    – itsazzad
    Jan 25, 2018 at 16:03
  • 14
    Yes, same security issues. The entire package.json will be included in the client bundle.
    – six5536
    Jun 26, 2018 at 11:58
159

Or in plain old shell:

node -e "console.log(require('./package.json').version);"

This can be shortened to

node -p "require('./package.json').version"
2
  • 5
    That's not within the nodeJS app itself though, as requested. Jan 7, 2016 at 6:16
  • I used this but it stopped working for Node 16 telling me SyntaxError: Unexpected token '.' - any ideas?
    – leonheess
    Dec 14, 2021 at 16:11
108

There are two ways of retrieving the version:

  1. Requiring package.json and getting the version:
const { version } = require('./package.json');
  1. Using the environment variables:
const version = process.env.npm_package_version;

Please don't use JSON.parse, fs.readFile, fs.readFileSync and don't use another npm modules it's not necessary for this question.

5
  • 5
    Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made.
    – milo526
    Feb 12, 2018 at 10:30
  • 27
    Then npm_* environment values are only available if your script was started by NPM, e.g. npm start. If you are doing node app.js or similar, they will not be present.
    – Nate
    Nov 8, 2018 at 20:50
  • @Nate So it is better to use version from package.json?
    – Filip Š
    Nov 25, 2018 at 20:33
  • You can also add a script "start": "node app.js" to your package.json and start your app using npm start—that'll give your the npm env vars Nov 19, 2021 at 16:44
  • This worked for me in typescript, just needed to add "resolveJsonModule": true to my config
    – killthrush
    Feb 12 at 13:17
84

Here is how to read the version out of package.json:

fs = require('fs')
json = JSON.parse(fs.readFileSync('package.json', 'utf8'))
version = json.version

Of other answers, probably the cleanest is:

const { version } = require('./package.json');

Here's the ES6 version:

import {version} from './package.json';
6
  • I've seen this a bunch, and I do like it - do you/anyone know the considerations that require() introduces? (for instance, does require()`not support utf8 reading? as your snippet may suggest)
    – electblake
    Sep 29, 2014 at 14:48
  • 5
    require() caches the file, which in this case should not make a difference.
    – jlee
    Nov 19, 2014 at 1:04
  • 1
    @jlee is there a reason people commonly do JSON.parse(fs.readFileSync('package.json', 'utf8')) instead of delete require.cache[require.resolve('package.json')]; require('package.json') when they want to reload? Feb 6, 2018 at 10:26
  • 2
    const { version } = require('./package.json');
    – аlex
    Feb 12, 2018 at 10:04
  • Any way using 'import' from ES6?
    – ed22
    Jan 8, 2023 at 16:31
81

For those who look for a safe client-side solution that also works on server-side, there is genversion. It is a command-line tool that reads the version from the nearest package.json and generates an importable CommonJS module file that exports the version. Disclaimer: I'm a maintainer.

$ genversion lib/version.js

I acknowledge the client-side safety was not OP's primary intention, but as discussed in answers by Mark Wallace and aug, it is highly relevant and also the reason I found this Q&A.

7
  • 9
    This is THE answer, and it needs more votes to get above the deeply problematic answer on top right now.
    – Jeff Allen
    May 30, 2018 at 13:37
  • 6
    Some people might be alarmed by the fact that this is a command line tool. Do not worry! The tool's readme describes how to (easily) integrate the call on build into package.json, so that you can forget about the existence of the tool and always will have the most recent version number.
    – malamut
    Aug 1, 2019 at 11:04
  • 3
    This should be the correct answer. Thanks @Akseli.
    – lcltj
    Dec 3, 2020 at 0:45
  • 1
    YES!!! This is the right answer. Nobody should be shipping their package.json file with their app. May 14, 2021 at 21:11
  • @EricJorgensen Brilliantly put, thank you :) May I quote your comment on the genversion repository README.md? May 16, 2021 at 20:35
40

NPM one liner:

From npm v7.20.0:

npm pkg get version

Prior to npm v7.20.0:

npm -s run env echo '$npm_package_version'

Note the output is slightly different between these two methods: the former outputs the version number surrounded by quotes (i.e. "1.0.0"), the latter without (i.e. 1.0.0).

One solution to remove the quotes in Unix is using xargs

npm pkg get version | xargs
1
  • Note that this only works in npm. If you're running something from node_modules/.bin with "#! /usr/bin/env node" you can't implement --version using this trick
    – Jason
    Jan 26, 2023 at 22:18
27

There is another way of fetching certain information from your package.json file, namely using the pkginfo module.

Usage of this module is very simple. You can get all package variables using:

require('pkginfo')(module);

Or only certain details (version in this case):

require('pkginfo')(module, 'version');

And your package variables will be set to module.exports (so the version number will be accessible via module.exports.version).

You could use the following code snippet:

require('pkginfo')(module, 'version');
console.log "Express server listening on port %d in %s mode %s", app.address().port, app.settings.env, module.exports.version

This module has very nice feature. It can be used in any file in your project (e.g., in subfolders) and it will automatically fetch information from your package.json file. So you do not have to worry where your package.json file is.

5
  • 2
    what is module here?
    – chovy
    Jan 29, 2017 at 1:29
  • 1
    @chovy, module is not this specific example variable; it is a variable representing the current module in node.js. You can read more about node.js modules here: nodejs.org/api/modules.html#modules_the_module_object
    – Tom
    Jan 29, 2017 at 15:24
  • 2
    I'm trying to get the version of other modules required by my module... and I'm having a hard time figuring out if pkginfo makes this possible.
    – Michael
    Sep 14, 2019 at 17:26
  • I tried using pkginfo with ES6 modules, but nothing worked. I can't see how you can translate require('pkginfo')(module) into import syntax.
    – icc97
    Sep 6, 2023 at 18:08
  • There is now npmjs.com/package/read-pkg which does something similar but is much more up-to-date and well maintained
    – icc97
    Sep 6, 2023 at 18:17
24

Option 1

Best practice is to version from package.json using npm environment variables.

process.env.npm_package_version

more information on: https://docs.npmjs.com/using-npm/config.html

This will work only when you start your service using NPM command.

Quick Info: you can read any values in pacakge.json using process.env.npm_package_[keyname]

Option 2

Setting version in environment variable using https://www.npmjs.com/package/dotenv as .env file and reading it as process.env.version

4
  • 1
    Nice and clean. Thank you! Jul 6, 2020 at 17:36
  • it's undefined for me.
    – user3064538
    Sep 28, 2021 at 9:04
  • @Boris - You are trying option 1 or 2?
    – Aravin
    Sep 29, 2021 at 10:14
  • Option 1 on Node 14, using ES modules. Maybe it's because I'm running my code with node index.js. How do I run a "bin": "my-bin.js" through npm?
    – user3064538
    Sep 29, 2021 at 18:35
18

we can read the version or other keys from package.json in two ways

1- using require and import the key required e.g:

const version = require('./package.json')

2 - using package_vars as mentioned in doc

process.env.npm_package_version
2
  • 1
    These are set by npm but not by the node binary, which means it won't work for the bin directory (my main use for needing this sort of information)
    – Jason
    Jan 26, 2023 at 22:21
  • Version 1 worked for me, but slightly different: import {version} from '../../package'
    – cpres
    May 2, 2023 at 17:40
16

Just adding an answer because I came to this question to see the best way to include the version from package.json in my web application.

I know this question is targetted for Node.js however, if you are using Webpack to bundle your app just a reminder the recommended way is to use the DefinePlugin to declare a global version in the config and reference that. So you could do in your webpack.config.json

const pkg = require('../../package.json');

...

plugins : [
    new webpack.DefinePlugin({
      AppVersion: JSON.stringify(pkg.version),
...

And then AppVersion is now a global that is available for you to use. Also make sure in your .eslintrc you ignore this via the globals prop

0
14

A safe option is to add an npm script that generates a separate version file:

"scripts": {
    "build": "yarn version:output && blitz build",
    "version:output": "echo 'export const Version = { version: \"'$npm_package_version.$(date +%s)'\" }' > version.js"
  }

This outputs version.js with the contents:

export const Version = { version: "1.0.1.1622225484" }
1
12

If you are looking for module (package.json: "type": "module") (ES6 import) support, e.g. coming from refactoring commonJS, you should (at the time of writing) do either:

import { readFile } from 'fs/promises';

const pkg = JSON.parse(await readFile(new URL('./package.json', import.meta.url)));

console.log(pkg.version)

or, run the node process with node --experimental-json-modules index.js to do:

import pkg from './package.json'
console.log(pkg.version)

You will however get a warning, until json modules will become generally available.

If you get Syntax or (top level) async errors, you are likely in a an older node version. Update to at least node@14.

1
  • This is the best answer. There's no better way than to do it yourself; No 3-P deps, and one line. Alternative(s): 1. Since Node v18 you can pass --resolveJsonModule at invocation to load modules with JSON extensions (no longer experimental). 2. Without any flags you can await top level - and also dynamically import: const VERSION = ( await import( 'package.json' ) ).version. Though, for simplicity: const version = JSON.parse( ( await fs.readFile( path.join( './', 'package.json' ), { encoding: 'utf8' } ) ) ).version;. Done (provide encoding - otherwise a Buffer is returned.)
    – Rik
    Oct 10, 2022 at 22:37
11

You can use ES6 to import package.json to retrieve version number and output the version on console.

import {name as app_name, version as app_version}  from './path/to/package.json';

console.log(`App ---- ${app_name}\nVersion ---- ${app_version}`);
1
  • 5
    This works as long as you set "resolveJsonModule" to "true" in tsconfig.json. Apr 24, 2019 at 4:36
9

To determine the package version in node code, you can use the following:

  1. const version = require('./package.json').version; for < ES6 versions

  2. import {version} from './package.json'; for ES6 version

  3. const version = process.env.npm_package_version; if application has been started using npm start, all npm_* environment variables become available.

  4. You can use following npm packages as well - root-require, pkginfo, project-version.

7

Why don't use the require resolve...

const packageJson = path.dirname(require.resolve('package-name')) + '/package.json';
const { version } = require(packageJson);
console.log('version', version)

With this approach work for all sub paths :)

7

I'm using create-react-app and I don't have process.env.npm_package_version available when executing my React-app.

I did not want to reference package.json in my client-code (because of exposing dangerous info to client, like package-versions), neither I wanted to install an another dependency (genversion).

I found out that I can reference version within package.json, by using $npm_package_version in my package.json:

"scripts": {
    "my_build_script": "REACT_APP_VERSION=$npm_package_version react-scripts start"
}

Now the version is always following the one in package.json.

6

You can use the project-version package.

$ npm install --save project-version

Then

const version = require('project-version');

console.log(version);
//=>  '1.0.0'

It uses process.env.npm_package_version but fallback on the version written in the package.json in case the env var is missing for some reason.

4
  • For example if the js file was started not from npm? Feb 6, 2018 at 10:08
  • 1
    Why would you want to add yet another package if it can be done so simply as @ÁngelBlanco suggests?!
    – Sander_P
    Jul 13, 2023 at 14:05
  • I wrote this in 2017, and I don't think the LTS version of node we had back then supported the ES6 syntax used by @ÁngelBlanco.
    – simonepri
    Jul 20, 2023 at 17:21
  • The project-version package uses github.com/sindresorhus/read-pkg - this package is much better maintained than project-version, so I would use read-pkg instead.
    – icc97
    Sep 6, 2023 at 18:14
5

The leanest way I found:

const { version } = JSON.parse(fs.readFileSync('./package.json'))
0
5

In case you want to get version of the target package.

import { version } from 'TARGET_PACKAGE/package.json';

Example:

import { version } from 'react/package.json';
5

I've actually been through most of the solutions here and they either did not work on both Windows and Linux/OSX, or didn't work at all, or relied on Unix shell tools like grep/awk/sed.

The accepted answer works technically, but it sucks your whole package.json into your build and that's a Bad Thing that only the desperate should use, temporarily to get unblocked, and in general should be avoided, at least for production code. One alternative is to use that method only to write the version to a single constant that can be used as a source file for the build, instead of the whole file.

So for anyone else looking for a cross-platform solution (not reliant on Unix shell commands) and local (without external dependencies):

Since it can be assumed that Node.js is installed, and it's already cross-platform for this, I just created a make_version.js file (or make_version.cjs in more recent environments) with:

const PACKAGE_VERSION = require("./package.json").version;
console.log(`export const PACKAGE_VERSION = "${PACKAGE_VERSION}";`);
console.error("package.json version:", PACKAGE_VERSION);

and added a version command to package.json:

scripts: {
    "version": "node make_version.js > src/version.js",

or

scripts: {
    "version": "node make_version.cjs > src/version.js",

(for a CommonJS file) and then added:

    "prebuild": "npm run version",
    "prestart": "npm run version",

and it creates a new src/versions.js on every start or build. Of course this can be easily tuned in the version script to be a different location, or in the make_version.js file to output different syntax and constant name, etc.

Note also that the pnpm package manager does not automatically run "pre" scripts, so you might need to adjust it for two commands if using that PM.

1
  • Note that with recent module support updates in Node and some ecosystems, in some environments you would actually need to name the above make_version.cjs (extension) rather than .js for this to continue to work correctly. I ran into this with Solid-Start and I suspect others will with Next, etc. Oct 16, 2023 at 22:45
5

I know this isn't the intent of the OP, but I just had to do this, so hope it helps the next person.

If you're using Docker Compose for your CI/CD process, you can get it this way!

version:
  image: node:7-alpine
  volumes:
    - .:/usr/src/service/
  working_dir: /usr/src/service/
  command: ash -c "node -p \"require('./package.json').version.replace('\n', '')\""

For the image, you can use any Node.js image. I use Alpine Linux, because it is the smallest.

3

I am using gitlab ci and want to automatically use the different versions to tag my docker images and push them. Now their default docker image does not include node so my version to do this in shell only is this

scripts/getCurrentVersion.sh

BASEDIR=$(dirname $0)
cat $BASEDIR/../package.json | grep '"version"' | head -n 1 | awk '{print $2}' | sed 's/"//g; s/,//g'

Now what this does is

  1. Print your package json
  2. Search for the lines with "version"
  3. Take only the first result
  4. Replace " and ,

Please not that i have my scripts in a subfolder with the according name in my repository. So if you don't change $BASEDIR/../package.json to $BASEDIR/package.json

Or if you want to be able to get major, minor and patch version I use this

scripts/getCurrentVersion.sh

VERSION_TYPE=$1
BASEDIR=$(dirname $0)
VERSION=$(cat $BASEDIR/../package.json | grep '"version"' | head -n 1 | awk '{print $2}' | sed 's/"//g; s/,//g')

if [ $VERSION_TYPE = "major" ]; then
  echo $(echo $VERSION | awk -F "." '{print $1}' )
elif [ $VERSION_TYPE = "minor" ]; then
  echo $(echo $VERSION | awk -F "." '{print $1"."$2}' )
else
  echo $VERSION
fi

this way if your version was 1.2.3. Your output would look like this

$ > sh ./getCurrentVersion.sh major
1

$> sh ./getCurrentVersion.sh minor
1.2

$> sh ./getCurrentVersion.sh
1.2.3

Now the only thing you will have to make sure is that your package version will be the first time in package.json that key is used otherwise you'll end up with the wrong version

2

I do this with findup-sync:

var findup = require('findup-sync');
var packagejson = require(findup('package.json'));
console.log(packagejson.version); // => '0.0.1' 
1
  • findup starts with cwd, so in most cases it would just get the top level package.json, similar to process.env.npm_package_version besides not requiring it to be started via npm. So trying to get your library version would actually get the caller's version. A simple require('./package.json') would avoid this. Feb 6, 2018 at 10:22
2

I made a useful code to get the parent module's package.json

function loadParentPackageJson() {
    if (!module.parent || !module.parent.filename) return null
    let dir = path.dirname(module.parent.filename)
    let maxDepth = 5
    let packageJson = null
    while (maxDepth > 0) {
        const packageJsonPath = `${dir}/package.json`
        const exists = existsSync(packageJsonPath)
        if (exists) {
            packageJson = require(packageJsonPath)
            break
        }
        dir = path.resolve(dir, '../')
        maxDepth--
    }
    return packageJson
}
2

If using rollup, the rollup-plugin-replace plugin can be used to add the version without exposing package.json to the client.

// rollup.config.js

import pkg from './package.json';
import { terser } from "rollup-plugin-terser";
import resolve from 'rollup-plugin-node-resolve';
import commonJS from 'rollup-plugin-commonjs'
import replace from 'rollup-plugin-replace';

export default {
  plugins: [
    replace({
      exclude: 'node_modules/**',
      'MY_PACKAGE_JSON_VERSION': pkg.version, // will replace 'MY_PACKAGE_JSON_VERSION' with package.json version throughout source code
    }),
  ]
};

Then, in the source code, anywhere where you want to have the package.json version, you would use the string 'MY_PACKAGE_JSON_VERSION'.

// src/index.js
export const packageVersion = 'MY_PACKAGE_JSON_VERSION' // replaced with actual version number in rollup.config.js
2

const { version } = require("./package.json");
console.log(version);

const v = require("./package.json").version;
console.log(v);

1

Import your package.json file into your server.js or app.js and then access package.json properties into server file.

var package = require('./package.json');

package variable contains all the data in package.json.

1
const packageJson = require('./package.json'); // Adjust the path if needed

const appVersion = packageJson.version;

console.log(`The version specified in package.json is: ${appVersion}`);

This code assumes that your package.json file is in the root directory of your Node.js application. If it's located in a different directory, adjust the require path accordingly.

This will log the version specified in your package.json to the console. You can use the appVersion variable in your application as needed.

Not the answer you're looking for? Browse other questions tagged or ask your own question.