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:
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.
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.