Sending command line arguments to npm script
To pass arguments to an npm script, use the --
syntax, and retrieve them in your Node.js script with process.argv
or the minimist
package.
Usage:
Retrieve in Node.js:
Understanding the Arguments
Comprehending command-line arguments involves distinguishing the node flags, npm flags, and script arguments respectively.
Node.js - I too get Arguments?
Node.js gives us process.argv
to access CLI arguments. Here's a way to parse them like a pro:
Parsing Package Power-Up
Utilize yargs
or minimist
to simplify the argument retrieval:
Command Line Meets Environment Variables
Environment variables add flexibility to npm scripts. They become especially handy while running applications in different environments.
Dynamic Ports? Yes, Please!
Setting the application's port dynamically can be done with environment variables:
Override it when you please:
Oh package.json, Hold this for Me
Here's how you can set and use environment variables within package.json
itself:
Npm_config, The Bearer
Npm allows passing arguments via environment variables prefixed with npm_config_
. Fetch them in your script as follows:
Invoke your script with the custom port:
Exploring Special Cases
Platform Peace
Windows and Unix-based systems handle environment variables differently. cross-env
is your platform-agnostic friend:
Update your scripts
:
Naming Etiquettes: Hyphens to Underscores
When working with npm_config_
variables, remember to replace hyphens with underscores in variable names:
Debugging and Best Practices
When things don't act as they should, console.log process.argv
. This will allow you to see what arguments Node.js is receiving.
Remember the --
convention for consistency across different tools and environments.
Think twice before passing sensitive data as arguments. These could be exposed in system-wide process listings – a security consideration to not overlook.
Was this article helpful?