Search code examples
yargs

How to structure one of many commands in yargs?


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?


Solution

  • 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