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:

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;
    }