node.js - 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;
在这里,我希望用户通过命令id
或first
选项read
此外,当使用无效选项运行此命令时,它不会显示错误
node app.js read --id=1 --first=1
yargs: ^12.0.5
解决方案
您可以使用check
API。
// 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 可以是选项值的字符串或布尔值
推荐阅读
- batch-file - 批处理 - 获取文件夹中所有视频的持续时间的最佳方法是什么?
- apache-beam - 通过代码从 Apache Beam 应用程序向 Google Cloud 进行身份验证
- amazon-web-services - Aws Glue Crawler 在第一次爬网后未更新表
- javascript - WebAuthn:无法创建公钥。承诺被拒绝
- javascript - 如何从一个文件中获取状态值并将其传递给 React 中的另一个文件
- github - 我可以使用 github 句柄推送到 gitlab 存储库吗?
- mysql - 您可以创建一个使用其他列数据的主键值吗?
- google-workspace - Google Workspace Reseller API:获取外拨电话信息 (Google Voice)
- node.js - Docker Desktop 无法使用 Node.js 子进程在 Windows 上初始化
- sql - 如何通过使用 spark-sql 将传入日期与当前年份和月份进行比较来验证日期