Node.js › CLI Tools & Scripting with Node.js
How would you parse command-line arguments and flags in a Node.js CLI tool using a library like commander or yargs?
IntermediateAnswer
Rather than manually parsing process.argv (which requires hand-written logic to distinguish flags, positional arguments, and their values), libraries like commander or yargs provide a declarative API for defining expected options, flags, and arguments, automatically generating help text, validating required arguments, and parsing values (including type coercion) with far less boilerplate than a hand-rolled parser.
const { program } = require('commander');
program
.option('-v, --verbose', 'enable verbose output')
.option('-o, --output <path>', 'output file path', 'default.txt')
.argument('<input>', 'input file to process')
.action((input, options) => {
console.log(`Processing ${input} -> ${options.output}`, options.verbose ? '(verbose)' : '');
});
program.parse();Real-world example A data-processing CLI tool uses commander to define a required input-file argument, an optional --output flag with a sensible default, and a --verbose boolean flag, automatically getting a properly formatted --help output and clear error messages for missing required arguments, without hand-writing any of that parsing logic.