1

I have read the yargs documetation multiple times, but can't figure out this one. Here are my requirements:

  • My CLI should provide two commands: cmd1 and cmd2.
  • The user must specify one of these two commands, otherwise the CLI must print a help message and exit.

This is my attempt:

async function main() {
  await yargs(process.argv.slice(2))
    .command('cmd1', 'Command 1', {}, () => console.log('Executing command1'))
    .command('cmd2', 'Command 2', {}, () => console.log('Executing command2'))
    .help().argv;
}

Following commands work as expected:

my-cli cmd1   # prints "Executing command1"
my-cli cmd2   # prints "Executing command2"

However following commands quit silently:

my-cli
my-cli cmd3

What am I missing?

Naresh
  • 23,937
  • 33
  • 132
  • 204
  • You can add `.strict()`: https://yargs.js.org/docs/#api-reference-strictenabledtrue – Raptor May 03 '22 at 04:44
  • 1
    Thank you so much, @Raptor. Refining this a bit, the combination that worked best for me was `.strictCommands()` + `.demandCommand(1)`. Would you mind adding an "official" answer? – Naresh May 03 '22 at 05:05
  • Done, thanks! Nice to hear that it helps you. – Raptor May 03 '22 at 06:23

1 Answers1

1

According to the documentation and the refine of OP, the correct yarg code handling undefined arguments is as follow:

async function main() {
  await yargs(process.argv.slice(2))
    .command('cmd1', 'Command 1', {}, () => console.log('Executing command1'))
    .command('cmd2', 'Command 2', {}, () => console.log('Executing command2'))
    .strictCommands()
    .demandCommand()
    .help().argv;
}
  • strictCommands(): accepts only defined commands (i.e. does not accept undefined command like cmd3) Documentation

  • demandCommand(): accepts minimum 1 argument (i.e. does not accept a command with no argument); 1 is the default value of minimum; can also add max option to constraint to exactly 1 argument by demandCommand(1, 1) Documentation

Raptor
  • 53,206
  • 45
  • 230
  • 366
  • 1
    Thank you, @Raptor. The yargs API is very wide and gets difficult to spot exactly what's needed. Your answer was a big help. – Naresh May 03 '22 at 11:49