npm run: pass command line arguments to an npm script
Codemia Knowledge Hub ·
Put -- after the script name: npm run start -- --mode=production --port=8080. Everything after the first -- is forwarded to the underlying command instead of being processed by npm. The script then reads the values from process.argv or with an argument parser; forwarding and parsing are separate steps.
Forward arguments with --
Given this package.json:
pass flags to app.js like this:
Without the -- separator, npm treats the flags as its own and the script never receives them.
Read the arguments in Node
Inside the script, the raw values are in process.argv:
Remember that the first entries of process.argv are the Node executable and the script path. For small scripts, a tiny helper is enough:
This works well when the script has only a few options and you control every call site.
Use a parser for nontrivial scripts
Once the flags get more complex, use an argument parser instead of hand-rolled string checks:
This is easier to extend and less fragile than custom parsing logic.
Nested npm scripts need forwarding too
When one npm script calls another, arguments only survive if you forward them:
Now this works:
If the intermediate script leaves out the extra --, the downstream script never sees the flags.
CLI flags vs environment variables
Not every setting belongs on the command line:
- use CLI flags for per-run toggles such as
--watchor--port - use environment variables for secrets or broader environment configuration
Example:
Then add ordinary runtime flags on top:
Command-line arguments can end up in logs, CI output or process listings, so pass secrets through environment variables or a secret store instead.
Related reading
- Sending html content in AWS SNSSimple Notification Service emails notifications
- Serializing to JSON in jQuery
- Set select option ''selected'', by value
- Set TextView text from html-formatted string resource in XML
- Set useState hook in a async loop
- setTimeout in React Native
- sh 1 react-scripts not found In Docker
- sh husky command not found
System design interview problems on this topic
- Design Google Doc: solution and walkthrough
- Design Facebook Messenger: solution and walkthrough
- Design Typeahead Suggestion: solution and walkthrough
- Design an Online Presence Indicator Service: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.