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

  • As @shadowspawn said, commander does not have support for this kind of construct. However you can simulate it by taking the mandatory parameter as an argument and make validation yourself. Then you can override the help output using the usage method. Something like this.

    const assertOnOff = (str) => {
      if (!/^(on|off)$/.test(str)) {
        Logger.error('Toggle action must be either `on` or `off`');
        process.exit(1);
      }
    };
    
    const expandJson = str => JSON.stringify(JSON.parse(str), null, 2);
    
    async function start(action, features) {
      assertOnOff(action);
      // ... do things
    }
    
    
    program.command('toggle <action> <FEATURE_NAME...>')
      .description('turns a feature on or off')
      .usage('(on|off) <FEATURE_NAME...>')
      .action(start);
    

    Then when you call the command like this

    toggle -h

    You will get this help output

    Usage: toggle (on|off) <FEATURE_NAME...>
    
    turns a feature on or off
    
    Options:
      -i, --institution [name]  Institution name
      -h, --help                output usage information