To pass command line arguments to a Node.js program and access them, you can use the built-in process.argv array or leverage libraries like yargs or commander for structured parsing. Here’s how:
1. Basic Method: Using process.argv
The process.argv array contains command line arguments provided when running the script.
Indexes:
0: Path to the Node.js executable.1: Path to the script file.2+: User-provided arguments.
Example:
// script.js
const args = process.argv.slice(2); // Extract user arguments
console.log("Arguments:", args);
Run:
node script.js arg1 arg2 --input=file.txt
Output:
Arguments: [ 'arg1', 'arg2', '--input=file.txt' ]
2. Structured Parsing with Libraries
A. Using yargs (Recommended)
Install:
npm install yargs
Example:
const yargs = require('yargs/yargs');
const { argv } = yargs(process.argv.slice(2))
.option('input', {
alias: 'i',
type: 'string',
description: 'Input file path'
})
.option('verbose', {
alias: 'v',
type: 'boolean',
description: 'Enable verbose logging'
});
console.log("Input file:", argv.input);
console.log("Verbose mode:", argv.verbose);
Run:
node script.js --input=data.csv --verbose
Output:
Input file: data.csv
Verbose mode: true
B. Using commander
Install:
npm install commander
Example:
const { program } = require('commander');
program
.name('my-script')
.description('CLI tool to process data')
.option('-i, --input <file>', 'Input file')
.option('-v, --verbose', 'Enable verbose mode');
program.parse(process.argv);
const options = program.opts();
console.log("Input file:", options.input);
console.log("Verbose mode:", options.verbose);
Run:
node script.js -i data.csv -v
3. Handling Positional Arguments
Use .command() in yargs to define positional arguments:
const argv = require('yargs/yargs')(process.argv.slice(2))
.command('<input> [output]', 'Process input and save to output')
.parse();
console.log("Input:", argv._[0]);
console.log("Output:", argv._[1]);
Run:
node script.js input.txt output.txt
Key Differences
| Method | Pros | Cons |
|---|---|---|
process.argv | No dependencies, simple for basic use. | Manual parsing for complex cases. |
yargs/commander | Auto-parsing, validation, help menus. | Adds dependencies. |
Best Practices
- Validate Inputs: Ensure arguments meet expected formats.
- Sanitize Values: Prevent security issues like path traversal.
- Use Help Menus: Libraries like
commanderauto-generate--help.
Choose process.argv for trivial cases and libraries like yargs/commander for complex CLI tools!