The scripts
portion of my package.json
currently looks like this:
"scripts": {
"start": "node ./script.js server"
}
...which means I can run npm start
to start the server. So far so good.
However, I would like to be able to run something like npm start 8080
and have the argument(s) passed to script.js
(e.g. npm start 8080
=> node ./script.js server 8080
). Is this possible?
jakub.g's answer is correct, however an example using grunt seems a bit complex.
So my simpler answer:
- Sending a command line argument to an npm script
Syntax for sending command line arguments to an npm script:
Imagine we have an npm start task in our package.json to kick off webpack dev server:
We run this from the command line with
npm start
Now if we want to pass in a port to the npm script:
running this and passing the port e.g. 5000 via command line would be as follows:
- Using package.json config:
As mentioned by jakub.g, you can alternatively set params in the config of your package.json
npm start
will use the port specified in your config, or alternatively you can override it- Setting a param in your npm script
An example of reading a variable set in your npm script. In this example
NODE_ENV
read NODE_ENV in server.js either prod or dev
You could also do that:
In
package.json
:In
cool.js
:In CLI:
Should output:
Update: Using npm 3.10.3, it appears that it lowercases the
process.env.npm_config_
variables? I'm also usingbetter-npm-run
, so I'm not sure if this is vanilla default behavior or not, but this answer is working. Instead ofprocess.env.npm_config_myVar
, tryprocess.env.npm_config_myvar
Use
process.argv
in your code then just provide a trailing$*
to your scripts value entry.echoargs.js:
package.json:
Examples:
process.argv[0]
is the executable (node),process.argv[1]
is your script.Tested with npm v5.3.0 and node v8.4.0
If you want to pass arguments to the middle of an npm script, as opposed to just having them appended to the end, then inline environment variables seem to work nicely:
Here,
npm run dev
passes the-w
watch flag to babel, butnpm run start
just runs a regular build once.I've found this question while I was trying to solve my issue with running sequelize seed:generate cli command:
Let me get to the point. I wanted to have a short script command in my package.json file and to provide --name argument at the same time
The answer came after some experiments. Here is my command in package.json
... and here is and example of running it in terminal to generate a seed file for a user
FYI
This doesn't really answer your question but you could always use environment variables instead:
Then in your server.js file: