Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 458
Abhik Bose Pramanik Avatar asked Feb 05 '12 22:02

Abhik Bose Pramanik


People also ask

How do I find the version of a package installed via npm?

Use npm view [package-name] version to know the specific latest version of a package available on the npm registry. Use npm list [package-name] to know the specific latest version of an installed package.

Is version required in package json?

Required name and version fieldsA package. json file must contain "name" and "version" fields. The "name" field contains your package's name, and must be lowercase and one word, and may contain hyphens and underscores.

How do I set node version in package json?

Use the engines keyword in the package. json file to specify the Node. js version that you want your application to use. You can also specify a version range using npm notation.


1 Answers

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.

like image 107
Mark Wallace Avatar answered Sep 30 '22 00:09

Mark Wallace