Topic 30 of 55
Command Line Arguments Parsing
Overview
When running a Node.js script, you can pass arguments to it via the terminal. These are captured in the process.argv array. This is the foundation for building custom CLI tools.
Syntax
javascript
// Running: node script.js --name Kartik --age 25
// In script.js
console.log(process.argv);
/*
Output is an array. The first two elements are always:
[
0: '/usr/local/bin/node', // Absolute path to the node executable
1: '/path/to/your/script.js', // Absolute path to the script being run
2: '--name', // Your actual arguments start here
3: 'Kartik',
4: '--age',
5: '25'
]
*/
// Slicing off the first two elements gets you just the user args
const args = process.argv.slice(2);
console.log(args); // [ '--name', 'Kartik', '--age', '25' ]Common Pitfalls
- Manually parsing
process.argvis tedious and error-prone because flags can be written as-n Kartikor--name=Kartik. Use a parsing library for production scripts. - All arguments in
process.argvare strings. If you pass a number (node app.js 42), you must manually convert it (parseInt(process.argv[2])).
Real-World Example
Using the built-in util.parseArgs (Node v18.3+) for easier parsing:
example
javascript
import { parseArgs } from 'node:util';
const args = ['--name', 'Kartik', '--admin'];
const options = {
name: { type: 'string' },
admin: { type: 'boolean', default: false },
};
const { values } = parseArgs({ args, options, strict: false });
console.log(values.name); // "Kartik"
console.log(values.admin); // true
// Note: For complex CLI apps, third-party libraries like 'commander' or 'yargs' are usually preferred.