How do I pass command line arguments to a Node.js program and receive them?
When running a Node.js program, you can supply additional command line arguments after the file name. For example:
node index.js arg1 arg2 arg3
Inside your Node.js script (e.g., index.js
), you can read these arguments using process.argv
, which is an array of strings:
process.argv[0]
: The path to the Node.js executable.process.argv[1]
: The path to the script file (e.g.,index.js
).process.argv[2]
onward: Actual command line arguments you passed.
1. Basic Usage
// index.js const args = process.argv.slice(2); // start from index 2 console.log('Received arguments:', args);
If you run:
node index.js arg1 arg2 arg3
It will print:
Received arguments: [ 'arg1', 'arg2', 'arg3' ]
Why slice(2)
?
- Indices
0
and1
represent paths to the Node binary and your script. - The real arguments start at index
2
.
2. Handling Named Arguments
If you want to pass and parse named arguments (like --name=Alice
), you can manually split strings or use a library (e.g., minimist, yargs).
Example with minimist
:
-
Install:
npm install minimist
-
Use:
// index.js const minimist = require('minimist'); const args = minimist(process.argv.slice(2)); console.log('Name:', args.name); console.log('Age:', args.age);
-
Run:
node index.js --name=Alice --age=30
Output:
Name: Alice Age: 30
3. Passing Arguments via npm Scripts
If you’re using npm run
scripts in your package.json
, you can pass additional arguments by placing --
after the script name:
{ "scripts": { "start": "node index.js" } }
Then in your terminal:
npm run start -- arg1 arg2
All arguments after --
will be forwarded to your Node.js script.
4. Best Practices and Tips
-
Parse Arguments Carefully
- If your application expects named options or flags (e.g.,
--debug
,--port=3000
), use a library like minimist or yargs to handle parsing consistently and reliably.
- If your application expects named options or flags (e.g.,
-
Validate User Inputs
- Don’t trust arguments blindly. Validate or sanitize arguments to avoid unexpected behavior.
-
Check for Missing/Extra Arguments
- If certain arguments are mandatory, display a help message or fallback defaults when they’re not provided.
-
Documentation
- Provide clear instructions or a
--help
option so users know how to supply and interpret command line arguments.
- Provide clear instructions or a
Recommended Resource
Summary
- Use
process.argv
in Node.js to access command line arguments. process.argv[2]
onward contains the actual arguments you pass.- For more advanced parsing (named arguments, flags), a library like minimist or yargs can simplify the process.
CONTRIBUTOR
TechGrind