7

I am new to commander and I am trying to achieve a command tree like this:

|- build
|    |- browser (+ options)
|    |- cordova (+ options)
|    |- no subcommands, just options
|- config
|    |- create (+ options)

Is it possible to split these commands up into multiple files, for example somewhat like this:

Central File:

const program = new commander.Command();
program.command('build').description(...);
program.command('config').description(...);

File for build command:

program.command('browser').description(...);
program.command('cordova').description(...);
program.option(...);

File for config command:

program.command('create').description(...);

I know of the Git-Style subcommands, but these seem to require executable files (I only have regular JS files)

shadowspawn
  • 3,039
  • 22
  • 26
Lehks
  • 2,582
  • 4
  • 19
  • 50

2 Answers2

10

There is an example in their documentation here:

const commander = require('commander');
const program = new commander.Command();
const brew = program.command('brew');
brew
  .command('tea')
  .action(() => {
    console.log('brew tea');
  });
brew
  .command('coffee')
  .action(() => {
    console.log('brew coffee');
  });

Example output:

$ node nestedCommands.js brew tea
brew tea

https://github.com/tj/commander.js/blob/master/examples/nestedCommands.js

Kim T
  • 5,770
  • 1
  • 52
  • 79
9

There is explicit support in Commander for standalone subcommand "executable" files with the .js file extension, without needing to set file permissions etc to make it directly executable on command line.

pm.js

const commander = require('commander');
const program = new commander.Command();
program
  .command('build', 'build description')
  .command('config', 'config description')
  .parse(process.argv);

pm-config.js

const commander = require('commander');
const program = new commander.Command();
program
  .command('create')
  .description('create description')
  .action(() => {
    console.log('Called create');
  });
program.parse(process.argv);
$ node pm.js config create
Called create
shadowspawn
  • 3,039
  • 22
  • 26
  • If I read the GitHub issues of commander correctly, there may have been an update regarding this functionality in commander5.0 – Martin J.H. Feb 10 '21 at 22:24
  • From Commander v5 you can have nested commands using just action handlers in a single program. Previously more than one layer of subcommands needed stand-alone executables. – shadowspawn Feb 11 '21 at 03:23
  • Subcommands can also be created and exported from their own files, and added to the parent command using `.addCommand()`. – shadowspawn Aug 05 '23 at 00:22