命令行参数语法
icore 接收 process.argv.slice(2),分离命令名称、位置参数和选项。所选命令的模式决定如何读取和验证值。支持以下四种形式。
- 长选项
--name value和--name=value。 - 布尔标志
--flag和--no-flag。 - 模式中声明的短名称,例如
-f和-n value。 - 位置参数之前的选项终止符
--。
长选项
将名称和值作为两个参数传入。
Shell
node dist/cli.js users get --name Alice
解析得到以下值。
JSON
{
"name": "Alice"
}
用等号连接也会得到同样的结果。
Shell
node dist/cli.js users get --name=Alice
字符串和数字选项可以接收以 - 开头的值。本例的模式将 label 声明为 type: 'string',将 limit 声明为 type: 'number'。
Shell
node dist/cli.js search --label -draft --limit -1
布尔标志
标志名将选项设为 true。
Shell
node dist/cli.js reports list --archived
如果模式允许取反,--no-<name> 会将已声明的布尔选项设为 false。
Shell
node dist/cli.js reports list --no-archived
等号后的显式值会被拒绝。
Shell
node dist/cli.js reports list --archived=true
node dist/cli.js reports list --archived=false
将值作为单独的参数传入时,archived 得到 true,而 false 仍为位置参数。
Shell
node dist/cli.js reports list --archived false
短名称
在选项模式中为 --verbose 指定 -v。
TypeScript
const options = {
verbose: {
type: 'boolean',
alias: 'v'
}
} as const;
用户可以使用短形式。
Shell
node dist/cli.js users get -v
处理函数通过长名称接收该值。
JSON
{
"verbose": true
}
对于字符串和数字选项,短名称及其值分别占用一个参数。
TypeScript
const options = {
name: {
type: 'string',
alias: 'n'
},
limit: {
type: 'number',
alias: 'l'
}
} as const;
Shell
node dist/cli.js users get -n Alice -l 10
JSON
{
"name": "Alice",
"limit": 10
}
紧接短名称的值会被拒绝。
Shell
node dist/cli.js users get -nAlice
请分别传入每个标志。一个参数中组合多个短名称会被拒绝。
Shell
node dist/cli.js users get -abc
选项终止符
-- 结束选项解析,并从结果中移除。之后的参数均视为位置参数,即使以 - 开头。
Shell
node dist/cli.js search -- --name Alice -v
命令名之后会保留位置参数 --name、Alice 和 -v。
重复选项
每个选项只传入一次。重复的长名称会被拒绝。
Shell
node dist/cli.js users get --format json --format table
同一选项同时使用长名称和短名称也会被视为重复。
Shell
node dist/cli.js users get --verbose -v
未知选项
未知长选项会触发验证错误。
Shell
node dist/cli.js users get --unknown value
未声明的短参数保留为位置参数。如果命令不允许额外的位置参数,验证会拒绝它。
全局标志、共享选项和重命名请参阅 CLI 模式。