Back to results for “CLI Tools & Scripting with Node.js”
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?

Intermediate

Answer

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.

Common follow-ups: How does commander automatically generate a --help output, and how would you customize it?;What's the difference in philosophy and API style between commander and yargs?