Get package.json fields

remarkablemark
1 min readJan 15, 2021

--

npm logo
npm

Get package.json fields using:

  • package.json vars
  • jq
  • node
  • awk

package.json vars

package.json vars are the npm package environment variables.

To print out all the package.json vars:

$ npm run env | grep npm_package_

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

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

node

Node.js can evaluate a script using 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:

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:

--

--

No responses yet