Get package.json fields


Get package.json fields using:

npm pkg

Retrieve the version of the current package with double quotes:

npm pkg get version

Retrieve the version of the current package without double quotes:

npm pkg get version | tr -d \"

package.json vars

package.json vars are the npm package environment variables.

Print out all the package.json vars:

npm run env | grep npm_package_

Get the “version” using a run-script:

// package.json
{
  "version": "1.2.3",
  "scripts": {
    "get-version": "echo $npm_package_version"
  }
}

Access an npm environment variable outside the scope of a run-script, parse the variable with bash:

npm run env | grep npm_package_version | cut -d '=' -f 2

jq

jq is a tool for filtering JSON.

To print the package.json version:

jq -r .version package.json

The -r option outputs the raw string (so it’s 1.2.3 instead of "1.2.3").

To get the “version” using a run-script:

// package.json
{
  "version": "1.2.3",
  "scripts": {
    "get-version": "jq -r .version package.json"
  }
}

node

Node.js can evaluate a script with the -e option.

To print the package.json version:

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

Pass the -p option to print the evaluation:

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

To get the “version” using a run-script:

// package.json
{
  "version": "1.2.3",
  "scripts": {
    "get-version": "node -p \"require('./package').version\""
  }
}

awk

awk is a tool that processes text.

To match package.json against the regex pattern /"version": ".+"/ and print the 4th field of the first result:

awk -F'"' '/"version": ".+"/{ print $4; exit; }' package.json

To get the “version” using a run-script:

// package.json
{
  "version": "1.2.3",
  "scripts": {
    "get-version": "awk -F'\"' '/\"version\": \".+\"/{ print $4; exit; }' package.json"
  }
}


Please support this site and join our Discord!