887

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
Patrick Lee Scott
  • 8,217
  • 3
  • 36
  • 42
Abhik Bose Pramanik
  • 9,181
  • 4
  • 16
  • 10
  • 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)` – Adrian Lynch Apr 28 '18 at 16:32

31 Answers31

1259

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.

Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
Mark Wallace
  • 12,726
  • 1
  • 14
  • 4
  • 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` – mikermcneil Jan 13 '14 at 02:40
  • @mikermcneil Rather than using `root-require`, you can also just delete the `require.cache` between requests since you know you don't want the cached version. Alternatively, it sounds like `__dirname` may have helped in your situation too. – bitsoflogic Apr 29 '15 at 14:43
  • 10
    Not working for my script with shebang installed globally. `Error: Cannot find module 'package.json'`. – exebook May 21 '15 at 11:39
  • huh, I would hope that process global var would have some info about the package.json file that was used to start the process. – Alexander Mills May 26 '15 at 17:43
  • 21
    shorter - require('./package').version – Afanasii Kurakin Jul 15 '15 at 07:09
  • Using a method to upgrade the version automatically as part of your build, like this: http://stackoverflow.com/questions/13059991/update-package-json-version-automatically, should also be a part of this answer. – HiDefLoLife Sep 23 '15 at 17:26
  • 83
    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 '15 at 23:03
  • How to get version of main package? _require('../../package.json')_ not work? – Gleb Jul 07 '16 at 15:19
  • 1
    Note that if you are using browserify, it probably means you are "packaging" your webapp in some way (whether that's just minifying, transpiling with babel, etc. etc.). If so, you can use the same method listed here, but don't do it in your application code -- do it in a custom browserify transform step. Perhaps your main app configuration can have a line like `Config.version = 'VERSION';`, your transform step just has to replace the string 'VERSION' with the version from package.json. Then your packaged app has access to the version without worrying about `package.json`. – Elliot Nelson Sep 03 '17 at 01:23
  • 12
    @Pathogen [genversion](https://www.npmjs.com/package/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. – Akseli Palén Oct 02 '17 at 22:41
  • 5
    `var pjson = require('package.json')` potentially will expose your whole `package.json`, which you most likely don't want to. Better option is answer by Julien Christin, which is using: `process.env.npm_package_version` – Mindaugas Apr 26 '18 at 12:19
  • 1
    There's better answers further down the page that don't have horrible security implications. – technogeek1995 Apr 02 '19 at 15:56
  • Could setting `pjson = null` after using the version attenuate the security issue? – Gerbus Apr 08 '19 at 20:32
  • 1
    No. If you reference the file it needs to include it in the build. It has nothing to do with in-memory. – theflowersoftime Sep 26 '19 at 17:43
  • easy, and simple to use – Nick Chan Abdullah Mar 20 '20 at 06:38
  • Warning! it will also create the following message [CommonJS or AMD dependencies can cause optimization bailouts](https://angular.io/guide/build#configuring-commonjs-dependencies) which should be avoided in typescripts project cause it "results in larger bundle sizes - Angular". – Raphaël Balet Oct 30 '20 at 07:04
  • 3
    Gonna vouch for [genversion](https://www.npmjs.com/package/genversion) here. As a TS user, it's real easy to add in a build step. Plus, I don't have to worry one bit that some dependent package will build my code in some way that exposes package.json. I'd much rather have the version number copied out (automagically) and exported to the rest of the code that way. – AverageHelper Apr 03 '21 at 23:22
689

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

process.env.npm_package_version

See package.json vars for more details.

Paolo
  • 20,112
  • 21
  • 72
  • 113
jchristin
  • 7,352
  • 2
  • 15
  • 18
  • 22
    this is probably the best answer since most of the information in package.json is attached to the process runtime variable – Alexander Mills Jun 19 '15 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 03 '15 at 16:29
  • 22
    And outside of node (e.g., shell scripts executed via `npm run …`) the version will be in the environment variable `$npm_package_version`. – Quinn Comendant Sep 11 '15 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 06 '16 at 05:58
  • 17
    It works within an [electron](http://electron.atom.io) app started with `npm start`, but not within a built electron app: for that, you can find it in [`app.getVersion`](http://electron.atom.io/docs/api/app/#appgetversion). – ChrisV Oct 09 '16 at 21:38
  • 1
    This does NOT return the version inside a NW.js (node-webkit) application. – Marc Oct 25 '16 at 07:59
  • @gbmhunter This worked in electron ran from the command line, but didn't work in the packaged version built with electron-builder :-( – Terrabits Mar 16 '17 at 22:50
  • 2
    FYI re: electron, `app.getVersion()` works in built electron apps, but (at least in my dev env), it _only_ works in built apps--dev env returns electron's version, so in renderer it'd be something like `process.env.npm_package_version || require('electron').remote.app.getVersion()` – Brandon Jun 19 '17 at 16:51
  • @jjrv it's not *incorrect* per se, as it is the version in the only package.json that was parsed by npm. The dependencies are loaded by node require and don't pass through npm. Furthermore, `process` is the node global and overwriting this property when entering a dependency would mean the value in the parent package and all other dependencies would change as well. – Mihail Malostanidis Feb 06 '18 at 10:16
  • @Brandon Actually I use `require('electron').app.getVersion()`. What's that `remote` you wrote? – LucaM Mar 29 '18 at 13:37
  • This looks like the safest way to get the version of your application. – Spencer Pollock Feb 13 '19 at 00:55
  • This does not seem to work with `yarn`--you may get an old version from the last time you ran the application with `npm`. – rosendin Aug 13 '21 at 05:50
  • 1
    If these variables are `undefined`, depending on your authoring environment you may need to forward these environment variables from the entry point run by Node.js to the part of your code that aims to access it. In my case, I was using Webpack and needed to add a [DefinePlugin](https://webpack.js.org/plugins/define-plugin/) to expose these `package.json` vars from the config file during the build process to the bundled code which was not ran by Node.js. – zr0gravity7 Sep 09 '21 at 13:47
  • Looks like it works with yarn on my end as well – Robin Métral Nov 19 '21 at 16:42
  • I wanted app version for an express server /status page. This did perfect. FWIW even though the prefix is 'npm' these work with yarn start as well – tbernard Apr 04 '22 at 16:43
  • This is the best way ! – F. Dakia Jun 20 '22 at 12:18
  • As of npm v7, only a few values are available using `process.env.npm_package_*`, despite the docs still saying otherwise. See [this issue](https://github.com/npm/cli/issues/2609) and [npm RFC21](https://github.com/npm/rfcs/blob/main/implemented/0021-reduce-lifecycle-script-environment.md). – aplum Aug 25 '22 at 13:53
  • This worked good for me! – leshugo33 Nov 16 '22 at 19:19
274

Using ES6 modules you can do the following:

import {version} from './package.json';
Patrick Lee Scott
  • 8,217
  • 3
  • 36
  • 42
  • 5
    I thought these were not supported in node: https://github.com/nodejs/help/issues/53 – ripper234 Feb 26 '17 at 19:24
  • 3
    No es6 modules are not yet directly supported but commonly used anyway, enabled using Babel – Patrick Lee Scott Feb 27 '17 at 14:52
  • It hides the other configurations like dependencies? I'm thinking to show the version in the home page of a Meteor application. – Sornii Aug 26 '17 at 04:48
  • 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 '17 at 09:58
  • I couldn't get the ES6 destructuring to work with jspm's json plugin – buddyp450 Nov 22 '17 at 14:16
  • Module not found: You attempted to import /package.json which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/. – Mark Buikema Jan 10 '18 at 16:17
  • 7
    Any security implication like as specified in https://stackoverflow.com/a/10855054/540144 ? – itsazzad Jan 25 '18 at 16:03
  • 13
    Yes, same security issues. The entire package.json will be included in the client bundle. – Relefant Jun 26 '18 at 11:58
  • 2
    On Node 14.17.6 I got `TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for /my/project/package.json` – Boris Verkhovskiy Sep 22 '21 at 02:26
  • 2
    @BorisVerkhovskiy (I know this is old) if you're using a "raw" Node program, like a command-line tool, Node currently does not know how to import JSON files via ES6 imports. The answer and other comments are based on work that some build tool does. When there's no build step, and you're basically doing `node mycode.js`, there does not seem to be a way to get at `package.json` short of reading it, which is itself problematic because the code would have to *find* it. – Pointy Jan 18 '23 at 16:59
  • This works great when building with Vite, and adding the version number statically with `define` in `vite.config.js/ts`. Only the version number will be added to the bundle, nothing else. Just make sure you `JSON.stringify(version)` so it will be included as a string. – ciscoheat Feb 11 '23 at 12:12
  • And here I was, struggling to import the `package.json` file in my ES6 ESM code! You are a lifesaver. – Fadhili Njagi Apr 19 '23 at 18:56
  • [See this other question I asked today, of course forgetting that I had found this previously.](https://stackoverflow.com/questions/76781496/node-program-module-reading-its-own-package-json-is-that-possible/76782867#76782867) There is a really reliable and easy way to do it, it turns out, from ES6 modules even. – Pointy Jul 27 '23 at 19:46
151

Or in plain old shell:

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

This can be shortened to

$ node -p "require('./package.json').version"
abernier
  • 27,030
  • 20
  • 83
  • 114
102

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.

Arian Acosta
  • 6,491
  • 1
  • 35
  • 32
аlex
  • 5,426
  • 1
  • 29
  • 38
  • 5
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation would greatly improve its long-term value](//meta.stackexchange.com/q/114762/206345) 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 '18 at 10:30
  • 26
    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 08 '18 at 20:50
  • @Nate So it is better to use version from `package.json`? – Filip Š Nov 25 '18 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 – Robin Métral Nov 19 '21 at 16:44
74

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.

Akseli Palén
  • 27,244
  • 10
  • 65
  • 75
  • 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 '18 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 01 '19 at 11:04
  • 3
    This should be the correct answer. Thanks @Akseli. – lcltj Dec 03 '20 at 00:45
  • 1
    YES!!! This is the right answer. Nobody should be shipping their package.json file with their app. – Eric Jorgensen May 14 '21 at 21:11
  • @EricJorgensen Brilliantly put, thank you :) May I quote your comment on the genversion repository README.md? – Akseli Palén May 16 '21 at 20:35
  • @Akseli - sure! – Eric Jorgensen May 18 '21 at 05:43
  • @Akseli - PS: I've been using genversion with my service and it has been working flawlessly. Thank you for creating this tool – Eric Jorgensen May 18 '21 at 05:44
68

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

EDIT: Wow, this answer was originally from 2012! There are several better answers now. Probably the cleanest is:

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

EDIT2: Well time keeps trucking along. Here's the ES6 version:

import {version} from './package.json';
Evan Moran
  • 3,825
  • 34
  • 20
  • 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 '14 at 14:48
  • 5
    `require()` caches the file, which in this case should not make a difference. – jlee Nov 19 '14 at 01: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? – Mihail Malostanidis Feb 06 '18 at 10:26
  • 1
    const { version } = require('./package.json'); – аlex Feb 12 '18 at 10:04
  • Any way using 'import' from ES6? – ed22 Jan 08 '23 at 16:31
32

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 echo
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Mbrevda
  • 2,888
  • 2
  • 27
  • 35
  • 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 '23 at 22:18
26

There is another way of fetching certain information from your package.json file namely using 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 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. So you do not have to worry where you package.json is.

I hope that will help.

Tom
  • 26,212
  • 21
  • 100
  • 111
  • 1
    what is `module` here? – chovy Jan 29 '17 at 01:29
  • @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: https://nodejs.org/api/modules.html#modules_the_module_object – Tom Jan 29 '17 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 '19 at 17:26
23

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

Aravin
  • 6,605
  • 5
  • 42
  • 58
17

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
Tawseef Bhat
  • 370
  • 4
  • 12
  • 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 '23 at 22:21
  • Version 1 worked for me, but slightly different: `import {version} from '../../package'` – cpres May 02 '23 at 17:40
15

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

aug
  • 11,138
  • 9
  • 72
  • 93
13

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" }
Carter
  • 1,184
  • 11
  • 5
11

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.

eljefedelrodeodeljefe
  • 6,304
  • 7
  • 29
  • 61
  • 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 '22 at 22:37
10

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}`);
ÁngelBlanco
  • 438
  • 4
  • 11
8

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.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
Rohit Jaiswal
  • 257
  • 4
  • 6
6

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

5

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.

simonepri
  • 493
  • 6
  • 11
5

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.

Ilmari Kumpula
  • 831
  • 1
  • 10
  • 18
4

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';
Long Nguyen
  • 9,898
  • 5
  • 53
  • 52
4

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. The alternative is to use that method only to write the version to a single constant that can be used 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 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",

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.

Appurist - Paul W
  • 1,291
  • 14
  • 22
3

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 image. I use alpine because it is the smallest.

Patrick Lee Scott
  • 8,217
  • 3
  • 36
  • 42
3

The leanest way I found:

const { version } = JSON.parse(fs.readFileSync('./package.json'))
vinyll
  • 11,017
  • 2
  • 48
  • 37
2

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

relief.melone
  • 3,042
  • 1
  • 28
  • 57
1

I do this with findup-sync:

var findup = require('findup-sync');
var packagejson = require(findup('package.json'));
console.log(packagejson.version); // => '0.0.1' 
mindrones
  • 1,173
  • 11
  • 15
  • 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. – Mihail Malostanidis Feb 06 '18 at 10:22
1

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
}
g00dnatur3
  • 1,173
  • 9
  • 16
1

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
spwisner
  • 59
  • 4
1

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

const v = require("./package.json").version;
console.log(v);
Johnty
  • 246
  • 1
  • 2
  • 18
0

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.

Aravind S
  • 2,347
  • 2
  • 12
  • 21
Patharraj
  • 41
  • 2
-1

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)

bikeman868
  • 2,236
  • 23
  • 30
-2

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

no_igor
  • 95
  • 1
  • 3