Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an npm cli option get package name from local package.json?

I want to get details from package.json on the command line. An example:

$ cd ~/my-node-package
$ npm commandiamlookingfor package name
my-package-name

I know this would be a trivial script to write. I could do it like this:

node -e "try {var pack=require('./package.json'); console.log(pack.name); } catch(e) {}"

But any code I don't have to write (and maintain) is the best code. Also, since I want to use this for shell integrations it will run a lot; a native implementation would maybe be faster.

like image 866
leff Avatar asked Apr 11 '16 23:04

leff


1 Answers

NPM has environment variables that it stores. You can see these by typing npm run env in the console.

You can use this to get the variable you need by grepping for npm_package_name but that leaves you with "npm_package_name=your_package_name".

One way to get around it would be to get the substring after the "=" character with the command:

cut -d "=" -f 2 <<< $(npm run env | grep "npm_package_name")

This command leaves you with the package name.

EDIT:
Another way to do this is by adding a script in your package.json that is simply echo $npm_package_name then run that script in your shell command.

Your package.json would look something like this:

{
  "name": "your_package_name",
  "scripts": {
      "getName": "echo $npm_package_name"
  }
}

Then type npm run getName -s

like image 133
Scott Hampton Avatar answered Oct 08 '22 10:10

Scott Hampton