gpt4 book ai didi

node.js - yargs 需要构建器选项之一

转载 作者:太空宇宙 更新时间:2023-11-03 22:49:22 24 4
gpt4 key购买 nike

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

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;

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

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

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

yargs:^12.0.5

最佳答案

您可以使用检查 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 可以是选项值的字符串或 bool 值

关于node.js - yargs 需要构建器选项之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54687136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com