Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Sending command line arguments to npm script

Sending command line arguments to npm script

Problem

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?

Problem courtesy of: arnemart

Solution

Edit 2014.10.30: It's possible to pass args to npm run as of npm 2.0.0

The syntax is as follows:

npm run [-- ]

Note the necessary --. It is needed to separate the params passed to npm command itself and params passed to your script.

So if you have in package.json

"scripts": {
    "grunt": "grunt",
    "server": "node server.js"
}

Then the equivalent of

grunt task:target

run via npm would be

npm run grunt -- task:target

and the equivalent of

node server.js --port=1337

will be

npm run server -- --port=1337


Edit 2013.10.03: It's not currently possible directly. But there's a related GitHub issue opened on npm to implement the behavior you're asking for. Seems the consensus is to have this implemented, but it depends on another issue being solved before.


Original answer: As a some kind of workaround (though not very handy), you can do as follows:

Say your package name from package.json is myPackage and you have also

"scripts": {
    "start": "node ./script.js server"
}

Then add in package.json:

"config": {
    "myPort": "8080"
}

And in your script.js:

// defaulting to 8080 in case if script invoked not via "npm run-script" but directly
var port = process.env.npm_package_config_myPort || 8080

That way, by default npm start will use 8080. You can however configure it (the value will be stored by npm in its internal storage):

npm config set myPackage:myPort 9090

Then, when invoking npm start, 9090 will be used (the default from package.json gets overridden).

Solution courtesy of: jakub.g

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Sending command line arguments to npm script

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×