Parsing Arguments Manually
What you'll learn: How to extract and validate command-line flags and values by looping through process.argv and checking patterns yourself.
When users pass flags like --name Alice or -v to your Node.js script, process.argv gives you a simple array of strings. But those strings aren't organized—you need to parse them yourself to turn them into usable data.
The Core Idea
Manual parsing means iterating through process.argv (starting at index 2, skipping node and the script path) and using pattern-matching logic to identify flags and their values.
Think of it like sorting mail: You read each envelope (argument), check if it's a flag (starts with - or --), and if it expects a value, grab the next envelope.
Basic Manual Parsing Pattern
const args = process.argv.slice(2);
const options = {};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '--name') {
options.name = args[i + 1]; // Next item is the value
i++; // Skip the value in next iteration
} else if (arg === '--verbose' || arg === '-v') {
options.verbose = true; // Boolean flag
}
}
console.log(options);
Running node script.js --name Alice -v produces:
{ name: 'Alice', verbose: true }
Validation Matters
Always check that expected values exist:
if (arg === '--port') {
const port = parseInt(args[i + 1], 10);
if (isNaN(port)) {
console.error('Invalid port number');
process.exit(1);
}
options.port = port;
i++;
}
Key Takeaway: Manual argument parsing means looping through process.argv, identifying flags with string checks, extracting their values from subsequent indices, and validating input—giving you full control but requiring careful handling of edge cases.