Abhik Bose Pramanik
Abhik Bose Pramanik

Reputation: 9771

Is there a way to get the version from the 'package.json' file in Node.js code?

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

Upvotes: 946

Views: 612356

Answers (30)


const fs = require("fs");

//Reach the package.json file
export function getPackageJson() {
  const path = `${process.cwd()}/package.json`;
  const packageData = JSON.parse(fs.readFileSync(path, "utf8"));
  return packageData;
}
const { name, version } = getPackageJson();

export const HealthEndpoint: Endpoint = {
  path: "/health",
  httpMethod: "GET",
  socket: true,
  handler: (source: HandlerSource) => {
    return {
      response: {
        error: false,
        status: "UP",
        service: name,
        version: version,
      },
    };
  },
};

Upvotes: 0

Patrick Lee Scott
Patrick Lee Scott

Reputation: 8719

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.

Upvotes: 6

Patrick Lee Scott
Patrick Lee Scott

Reputation: 8719

Using ES6 modules, you can do the following:

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

Upvotes: 306

abernier
abernier

Reputation: 28218

Or in plain old shell:

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

This can be shortened to

node -p "require('./package.json').version"

Upvotes: 168

Tom
Tom

Reputation: 26839

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.

Upvotes: 27

Evan Moran
Evan Moran

Reputation: 4173

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';

Upvotes: 86

Ravi Ranjan
Ravi Ranjan

Reputation: 287

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; 

Upvotes: -4

Krunal Dave
Krunal Dave

Reputation: 47

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.

Upvotes: 1

Mbrevda
Mbrevda

Reputation: 3090

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

Upvotes: 45

Appurist - Paul W
Appurist - Paul W

Reputation: 1468

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.

Upvotes: 5

bikeman868
bikeman868

Reputation: 2637

This is a very simple method that works in all environments. My app is written in TypeScript, but the changes to JavaScript are minor.

Add this script to package.json

"scripts": {
  "generate:buildinfo": "echo 'export default { version: \"'$npm_package_version'\", date: new Date('$(date +%s)'000) }' > ./src/buildInfo.ts",
  "prebuild": "npm run generate:buildinfo"
}

In some other TypeScript file:

import buildInfo from 'buildInfo.js'
console.log(buildInfo.version, buildInfo.date)

Upvotes: 0

Ilmari Kumpula
Ilmari Kumpula

Reputation: 1493

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.

Upvotes: 7

Tawseef Bhat
Tawseef Bhat

Reputation: 480

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

Upvotes: 19

Mark Wallace
Mark Wallace

Reputation: 13122

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.

Upvotes: 1297

Carter
Carter

Reputation: 1294

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" }

Upvotes: 15

eljefedelrodeodeljefe
eljefedelrodeodeljefe

Reputation: 6801

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.

Upvotes: 11

no_igor
no_igor

Reputation: 93

Used to version web-components like this:

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

class Widget extends HTMLElement {

  constructor() {
    super()
    this.attachShadow({ mode: 'open' })
  }

  public connectedCallback(): void {
    this.renderWidget()
  }

  public renderWidget = (): void => {
    this.shadowRoot?.appendChild(this.setPageTemplate())
    this.setAttribute('version', version)
  }
}

Upvotes: -2

Long Nguyen
Long Nguyen

Reputation: 10984

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';

Upvotes: 5

jchristin
jchristin

Reputation: 8096

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

process.env.npm_package_version

See package.json vars for more details.

Upvotes: 759

relief.melone
relief.melone

Reputation: 3322

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

Upvotes: 3

Johnty
Johnty

Reputation: 264

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

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

Upvotes: 2

vinyll
vinyll

Reputation: 11429

The leanest way I found:

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

Upvotes: 5

Aravin
Aravin

Reputation: 7087

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

Upvotes: 25

spwisner
spwisner

Reputation: 79

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

Upvotes: 2

аlex
аlex

Reputation: 5698

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.

Upvotes: 110

Gianluca Cirone
Gianluca Cirone

Reputation: 99

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 :)

Upvotes: 7

Rohit Jaiswal
Rohit Jaiswal

Reputation: 287

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.

Upvotes: 9

&#193;ngelBlanco
&#193;ngelBlanco

Reputation: 458

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}`);

Upvotes: 11

g00dnatur3
g00dnatur3

Reputation: 1193

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
}

Upvotes: 2

Patharraj
Patharraj

Reputation: 51

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.

Upvotes: 1

Related Questions