How to send parameters to an npm script defined in package.json?

I’m trying to figure out how to give extra info to an npm script that’s in my package.json file. Here’s what I’ve got:

{
  "scripts": {
    "start": "node app.js $1 $2 | ./node_modules/.bin/pretty-output"
  }
}

I want to run it like this from the command line:
npm run start 3000 dev

Then in my app.js file, I want to grab those extra bits (3000 and dev) using process.argv. Is this possible? How can I make it work? I’ve tried a few things but nothing seems to do the trick. Any help would be great!

I’ve dealt with this exact issue before, and there’s a simple solution. Instead of using $1 and $2 in your package.json script, you need to use – followed by your arguments. Here’s how you’d modify your script:

{
  "scripts": {
    "start": "node app.js -- | ./node_modules/.bin/pretty-output"
  }
}

Then, you can run it like this:
npm run start -- 3000 dev

In your app.js, you can access these arguments using process.argv.slice(2). The first two elements of process.argv are always the node executable and the script file, so we slice those off.

This method has worked reliably for me across different projects and npm versions. Just remember to include the – before your arguments when running the script.

hey sofiap, I’ve got a trick for ya. try using – after the script name when you run it. like this:

npm run start – 3000 dev

then in ur app.js, you can grab those args with process.argv.slice(2). Works like a charm for me!

Another approach you might consider is using environment variables. You can modify your script like this:

{
  "scripts": {
    "start": "PORT=$npm_config_port ENV=$npm_config_env node app.js | ./node_modules/.bin/pretty-output"
  }
}

Then run it as:
npm run start --port=3000 --env=dev

In your app.js, access these with process.env.PORT and process.env.ENV. This method is cleaner and more explicit, especially for scripts with multiple parameters. It also allows you to set default values in your code if the variables aren’t provided.