Getting your npm package version from bash

This question came up for me and since I spent more than 5 minutes looking it up and didn’t find this answer anywhere else I wanted to document it.

The way to do it through npm is to add a script to your package.json file like so:

  "name": "example",
  "version": "1.0.0",
  "scripts": {
    "version": "echo $npm_package_version"

Then you can do this to get the version from bash:

$ CURRENT_VERSION=$(npm run version --silent)

If you want to do automation as npm scripts, you can just access the $npm_package_version variable directly in your scripts.

The longer explanation here is that when you run an npm script it will automatically pull out all of the values from the package.json and put them into environment variables with the pattern npm_package_*. This means you can expose those variables as scripts if you want to use them externally.

The alternate version that I saw elsewhere was to just grab it using node like so:

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

I’m officially a node.js contributor.

This was a couple months ago but I forgot to mention it here!

Here is the commit:

The problem was that, on Windows, loading a native module with a file system path that was longer than 256 characters hit the classic MAX_PATH windows issue. Node actually has a way to successfully load files with long paths, and that way was applied to all path handling except in this one particular spot. It just so happened that I was the only person in the world trying to load native modules from a long path on windows it seems!