'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.
Solution 1:[1]
If you decide to go with your initial idea of using the node command, you could make it a bit cleaner by using the -p argument, which is shorthand for --print:
node -p "require('./package.json').name"
or with error handling
node -p "try { require('./package.json').name } catch(e) {}"
Solution 2:[2]
I also needed this but I try to keep node out of it since I never know if the docker container I will be using to run the script will actually have node installed (this is also why I won't use jq). I usually use this shell script
npm run env | grep "npm_package_name" | awk -F "=" '{print $2}'
Basically what it does is
- get env of npm package
- grep the line with "npm_package_name"
- split on "=" and return second entry
Solution 3:[3]
If you are a sed-o-phile: npm run env | sed -n '/npm_package_name/{s/.*=//;p;}'
The -n switch suppress auto print
The /npm_package_name/ address pattern selects for that line
{ starts a command block
s/.*=//; substitutes everything through the equal sign with nothing
p; prints the buffer
} ends the command block
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user56reinstatemonica8 |
| Solution 2 | |
| Solution 3 | Jeff |
