Is there a way to get version from package.json in nodejs code?

Is there a way to get the version set in package.json in a nodejs app? 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

Solution 1:

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.

Solution 2:

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

process.env.npm_package_version

See package.json vars for more details.

Solution 3:

Using ES6 modules you can do the following:

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

Solution 4:

Or in plain old shell:

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

This can be shortened to

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

Solution 5:

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.