Search code examples
node.jsecmascript-6node-modulesnode-commander

In Node Commander how to render all options for a command if it's options are not passed?


In Commander if the CLI is ran without specifying a command I get something like:

Options:
  -h, --help      display help for command

Commands:
  foo [options]  Foo
  bar [options]   Bar
  help [command]  display help for command

but if I run the CLI as:

app foo

I'd like to return all available options for that sole command.

Code

const foo = () => {
  program
    .command('foo')
    .description('This is a foo')
    .option('-a, --alpha [string]', 'Show Alpha', false)
    .option('-b, --beta [string]', 'Show Beta', false)
    .action(async options => {
      clear()
      try {
        const { alpha, beta } = options
        if (alpha === false && beta === false) return program.help()
      } catch (e) {
        console.log(chalk.red('Error: '), chalk.white(e.message))
        return process.exit(1)
      }
    })
}

export default foo

However program.help() doesn't specify the command's options but shows the output like in the first example.

Research

In Commander how to return options for a command if no option is passed?


Solution

  • To display the help for the subcommand, you use the subcommand to display the help. The action handler is passed the command to make this easy from an arrow function.

        .action(async (options, cmd) => {
           // ...
           cmd.help();
           }
    

    (Disclaimer: I am a maintainer of Commander.)