This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Commander.js CLI Library Cheat Sheet

A quick reference guide for Commander.js, the command-line interface solution for Node.js: option flags, commands, argument parsing, and custom help displays.

· Published

Commander.js is the complete solution for Node.js command-line interfaces.

Basic CLI Setup

const { program } = require('commander');

program
  .name('my-cli')
  .description('Sample CLI utility written in Node.js')
  .version('1.0.0');

Parsing Options

program
  .option('-p, --port <number>', 'specify port number', 3000)
  .option('-s, --silent', 'suppress terminal output')
  .option('-e, --env <mode>', 'execution environment', 'development')
  .requiredOption('-c, --config <path>', 'path to configuration file');

program.parse(process.argv);

const options = program.opts();
console.log(options.port, options.silent, options.config);
  • <value>: Required argument value.
  • [value]: Optional argument value.
  • Flags without value parameters act as boolean toggles.

Subcommands

program
  .command('clone <source> [destination]')
  .description('clone a repository into a directory')
  .option('-b, --branch <name>', 'clone a specific branch')
  .action((source, destination, cmdOptions) => {
    console.log(`Cloning ${source} into ${destination || '.'}`);
  });

program.parse();

Customizing Help

// Add custom footer text to --help output
program.addHelpText('after', `
Example call:
  $ my-cli -c ./app.json --port 8080
`);

// Manually display help
program.outputHelp();

Related topics