Search code examples
javascriptnode.jscommand-line-interfacenode-commander

mandatory arguments with commander-js


I was wondering if it is possible to create a command on commander that looks like this

toggle (on|off) <args...>

Where (on|off) means that you must choose one or the other, mandatory.

Ideally, commander should take care of throwing the appropriate error and error message.


Solution

  • This is supported from Commander version 8.

    import { Command, Argument } from 'commander';
    const program = new Command();
    
    program.command('toggle')
      .addArgument(new Argument('<state>', 'toggle state').choices(['on', 'off']))
      .argument('<args...>', 'further arguments')
      .action((state, args) => {
        console.log('state:', state);
        console.log('args:', args);
      });
    
    program.parse();
    
    $ node index.mjs toggle purple 1 2 3
    error: command-argument value 'purple' is invalid for argument 'state'. Allowed choices are on, off.
    $ node index.mjs toggle on 1 2 3    
    state: on
    args: [ '1', '2', '3' ]
    $ node index.mjs toggle --help
    Usage: index toggle [options] <state> <args...>
    
    Arguments:
      state       toggle state (choices: "on", "off")
      args        further arguments
    
    Options:
      -h, --help  display help for command