2

Here is a simple example of adding command in nodejs using commander:

'use strict';

const {Command} = require('commander');

const run = () => {
    const program = new Command();

    console.log('CMD');
    program.command('cmd [opts...]')
        .action((opts) => {
            console.log('OPTS');
        });

    program.parse(process.argv);
};

run();

In this case everything works fine, but when I'm adding description and options, commander throws an error:

program.command('cmd [opts...]', 'DESCRIPTION', {isDefault: true})

node test-commander.js cmd opts

test-commander-cmd(1) does not exist, try --help

My env:

node v8.9.3
npm 5.3.0
commander 2.12.2
Rostislav Shtanko
  • 704
  • 2
  • 9
  • 30

2 Answers2

0

That is the declared behavior of commander. From the npm page under Git-style sub-commands...

When .command() is invoked with a description argument, no .action(callback) should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like git(1) and other popular tools. The commander will try to search the executables in the directory of the entry script (like ./examples/pm) with the name program-command, like pm-install, pm-search.

So, when you add a description like you have, it'll assume you have another executable file called test-commander-cmd for the sub command.

If commander's behavior is not what you were expecting, I might recommend looking into a package I published, called wily-cli... only if you're not committed to commander, of course ;)

Assuming your code rests in file.js, your example with wily-cli would look like this...

const cli = require('wily-cli');

const run = () => {
  cli
    .command('cmd [opts...]', 'DESCRIPTION', (options, parameters) => { console.log(parameters.opts); })
    .defaultCommand('cmd');
};

run();

// "node file.js option1 option2" will output "[ 'option1', 'option2' ]"
Jason
  • 109
  • 4
0

As I landed this ancient thread experiencing the same issue, giving my answer it may be useful for others who will land here in their search. You should add description not to command call, but with separate call

command.description('Description Text');

In this case Commander behavior is different and it will not ignore the action call of command setup.

const group = program.command('group');
group.command('add <item>`).description('Add something to group`).action(() => {
   //do something
});
group.command('remove <item>`).description('Remove something from group`).action(() => {
   //do something
});

Kote Isaev
  • 273
  • 4
  • 13