鉴于以下cli
配置,我们可以通过将命令式控件放入动作处理程序中来验证传递的参数。
#!/usr/bin/env node
var program = require('commander');
program
.command('greet <person>')
.action((person, cmd) => {
console.log(`Hello ${person}`);
})
program.parse(process.argv)
但是,我想知道是否有实际的api:
program.command('greet <Giuseppe|Mick|Bob>');
因此,如果参数不正确,commanderjs
将自动抛出。
答案 0 :(得分:1)
command
参数的原理是它们可以是任何东西,因此必须在action
中进行处理。
如果您要使用一组有限的选项,则可能要使用option
。
通常可以解决此问题的一种解决方法是使用git-style sub-commands:
#!/usr/bin/env node
// main entry point for the program, let's call it mycmd
const program = require('commander');
program.command('greet', 'greets someone');
program.parse(process.argv);
然后有greet
命令文件:
#!/usr/bin/env node
// entry point for `greet` subcommand, named mycmd-greet
const program = require('commander');
// declare all available cases
// (you could also obviously reuse the same function as the action callback)
program
.command('giuseppe')
.action(() => {
console.log("Hi Giu!");
});
program
.command('mick')
.action(() => {
console.log("Hey Micky!");
});
program
.command('bob')
.action(() => {
console.log("That's my Bobby!");
});
// handle `greet` failures here in one shot
program
.command('*')
.action((x) => {
console.log(`Sorry, I don't know no ${x}.`);
});
program.parse(process.argv);
希望这会有所帮助!