首页 > 解决方案 > yargs 需要 builder 选项之一

问题描述

如何从命令中的构建器对象中要求我的选项之一

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;

在这里,我希望用户通过命令idfirst选项read

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

node app.js read --id=1 --first=1

yargs: ^12.0.5

标签: node.jsnpmyargs

解决方案


您可以使用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'));
        }
    })

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


推荐阅读