Nested commands with commander
Asked Answered
W

1

5

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

Winzler answered 20/2, 2021 at 15:43 Comment(0)
D
10

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

Dearly answered 21/2, 2021 at 1:2 Comment(2)
Can you add deeply nested commands? Like foo groups something other create?Simpleton
Yes. Just add each new subcommand to the previous command and build up a chain.Dearly

© 2022 - 2024 — McMap. All rights reserved.