yargs 需要构建器选项之一

ARI*_*ANA 3 node.js npm yargs

如何从命令中要求生成器对象中的选项之一

require('yargs')
  .usage('Usage: $0 <cmd> [options]')
  .command(
    'read',
    'Read a note',
    {
      id: {
        demand: true,
        string: true
      },
      first: {
        demand: true,
        boolean: true
      }
    },
    argv => {
      note.read(argv.id).then(data => {
        console.log('==================note read==================');
        console.log(data);
        console.log('==================note read==================');
      });
    }
  )
  .help()
  .strict().argv;
Run Code Online (Sandbox Code Playgroud)

在这里我希望用户传递命令的idfirst选项read

此外,当使用无效选项运行此命令时,它不会显示错误

node app.js read --id=1 --first=1
Run Code Online (Sandbox Code Playgroud)

yargs: ^12.0.5

Sou*_*abh 5

您可以使用checkAPI​​。

// code is written for logic purpose. Not tested.
.check(function (argv) {
        if ((argv.id && !argv.first) || (!argv.id && argv.first)) {
           return true;
        } else if (argv.id && argv.first) {
           throw(new Error('Error: pass either id or first option for read command'));
        } else {
           throw(new Error('Error: pass either id or first option for read command'));
        }
    })
Run Code Online (Sandbox Code Playgroud)

PS:1 可以是选项值的字符串或布尔值