How to pass arguments to an npm script from the command line?

Hey everyone! I’m trying to figure out how to send extra info to my npm script when I run it. Right now, my package.json has this in the scripts part:

"scripts": {
  "run-app": "node ./app.js start"
}

This works fine when I type npm run run-app. But what if I want to add more stuff? Like, how can I do npm run run-app 3000 and make it run node ./app.js start 3000? Is there a way to do this?

I’ve been scratching my head over this for a while. It would be super helpful if I could pass different port numbers or other settings without changing the script every time. Any ideas on how to make this work? Thanks in advance for any help!

hey luna23, try this: use npm run run-app – 3000 and it triggers node ./app.js start 3000. works wonders when u need quick port switching. i’ve used it alot, trust me!

You can actually pass arguments to npm scripts quite easily. Just add – after your npm command, followed by the arguments you want to pass. So in your case, you’d run:

npm run run-app – 3000

This will execute node ./app.js start 3000. Everything after the – gets appended to your script command.

In your package.json, you can also use $npm_config_argv to access these arguments. This gives you more flexibility in how you handle them in your script.

I’ve used this approach in several projects, especially for passing environment variables or configuration options. It’s really handy for CI/CD pipelines where you might need different settings for various environments.

As someone who’s been in your shoes, I can tell you that passing arguments to npm scripts is totally doable and super useful. Here’s what I’ve learned:

You can use the double dash (–) after your npm run command to pass arguments. So for your case, you’d do:

npm run run-app – 3000

This effectively runs node ./app.js start 3000. I’ve used this trick countless times in my projects, especially when I need to switch between different environments or configurations on the fly.

One cool thing I discovered is that you can also use npm config set to create custom configurations. For example:

npm config set myapp:port 3000
npm run run-app

Then in your script, you can access it with process.env.npm_config_myapp_port. This approach has saved me tons of time when dealing with complex setups across different environments.

Hope this helps! Let me know if you need any clarification.