Search code examples
javascriptnode.jsnode-commander

Nested commands with commander


I have the following code

export const program = new Command();

program.version('0.0.1');

program
  .command('groups')
  .command('create')
  .action(() => console.log('creating'))
  .command('delete')
  .action(() => console.log('deleting-all'))

program.parse(process.argv)

What I want to achieve is something like

groups create and groups delete

The code however chains that delete to the create. It recognizes groups create and groups create delete (which I dont want) but does not recognize the groups delete


Solution

  • You want to add the delete subcommand to the groups command. e.g.

    const { Command } = require('commander');
    
    const program = new Command();
    
    program.version('0.0.1');
    
    const groups = program
      .command('groups');
    groups
      .command('create')
      .action(() => console.log('creating'))
    groups
      .command('delete')
      .action(() => console.log('deleting-all'))
    
    program.parse(process.argv)
    

    The related example file is: https://github.com/tj/commander.js/blob/master/examples/nestedCommands.js