[英]How to structure one of many commands in yargs?
I have read the yargs documetation multiple times, but can't figure out this one.我已经多次阅读 yargs 文档,但无法弄清楚这一点。 Here are my requirements:这是我的要求:
cmd1
and cmd2
.我的 CLI 应该提供两个命令: cmd1
和cmd2
。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?我错过了什么?
According to the documentation and the refine of OP, the correct yarg
code handling undefined arguments is as follow:根据文档和 OP 的改进,正确的yarg
代码处理未定义的 arguments 如下:
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;
}
strictCommands()
: accepts only defined commands (ie does not accept undefined command like cmd3
) Documentation strictCommands()
:仅接受已定义的命令(即不接受未定义的命令,如cmd3
) 文档
demandCommand()
: accepts minimum 1 argument (ie does not accept a command with no argument); demandCommand()
:接受最少 1 个参数(即不接受没有参数的命令); 1 is the default value of minimum; 1为默认最小值; can also add max
option to constraint to exactly 1 argument by demandCommand(1, 1)
Documentation还可以通过demandCommand(1, 1)
文档将max
选项添加到恰好 1 个参数的约束
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.