Update Chinese docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Wang Weixuan · committed by Tomoaki Abe · parent 6f51e4a · Browse files · 5 files·+265 added−129 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+265 added−129 removed
- other:+265 added−129 removed
Provenance
- Commit
e6943c4- Tree
34561df- Author
Wang Weixuan <wangweixvan@gmail.com>- Committer
Tomoaki Abe <abe@enzou.tokyo>- Parent
6f51e4a
5 files changed+265 added−129 removed
modified:docs/zh-CN/不再推荐使用的功能.md+61 added-8 removed
123345656782 unmodified lines111213141715161718195 unmodified lines252627283129303132333437353637383940414243464445464748495034 unmodified lines85868788898990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142# 不再推荐使用的功能
本文中列出的功能不再推荐使用。它们在未来版本的Commander 中可能被移除。为保证后向兼容,这些功能目前还可以使用,但它们不应被用在新代码中。本文中列出的功能不再推荐使用。它们在 Commander 未来的主要版本(major version)中可能被移除。为保证后向兼容,这些功能目前还可以使用,但它们不应被用在新代码中。
Note: this document still describes Commander v7 and has not yet been updated for Commander v8.
## .option() 方法的正则表达式参数
`.option()`方法可以接受一个正则表达式作为第三个参数,以规定可以接受的选项参数值。
2 unmodified lines```
该功能从 Commander v3 的文档中被移除。自 Commander v7 起,该功能不再推荐使用。
新的写法是使用 Option 对象的`.choices()`方法,或者使用自定义选项处理函数。新的写法是使用`Option`对象的`.choices()`方法,或者使用自定义选项处理函数。
## noHelp
此选项曾被用作传入`.command()`方法,以在内建的帮助信息中隐藏该命令:5 unmodified lines在 Commander v5.1 中,该选项被更名为`hidden`。自 Commander v7 起`noHelp`不再推荐使用。
## 默认导入的全局 Command 对象
Commander 的默认导入曾是一个全局的 Command 对象。Commander 的默认导入曾是一个全局的`Command`对象。
```jsconst program = require('commander');```
自 Commander v5 后,全局 Command 对象作为 `program`被导出。或者也可以导入 `Command` 对象。自 Commander v5 后,全局`Command`对象作为 `program`被导出。或者也可以导入`Command`对象。
```jsconst { program } = require('commander');// 或者const { Command } = require('commander');comnst program = new Command()```
此功能在 Commander v5 的文档中被移除。自 Commander v7 起不再推荐使用。- 此功能在 Commander v5 的文档中被移除。- 自 Commander v7 起不再推荐使用。- 在 Commander v8 的 TypeScript 定义文件中被移除。
## .help() 与 .outputHelp() 的回调函数参数
这两个方法曾允许传入一个回调函数,以在展示前处理帮助信息。34 unmodified lines $ custom-help -h`);```
原功能自 Commander v7 起不再推荐使用。No newline at end of file原功能自 Commander v7 起不再推荐使用。
## cmd.description(cmdDescription, argDescriptions)
此功能曾用来为命令参数添加描述信息。
```jsprogram .command('price <book>') .description('show price of book', { book: 'ISBN number for book' });```
新的写法是使用`.argument()`方法。
```jsprogram .command('price') .description('show price of book') .argument('<book>', 'ISBN number for book');```
原功能自 Commander v8 起不再推荐使用。
## InvalidOptionArgumentError
此类曾被用来在自定义选项处理中抛出错误,以显示错误信息。
```jsfunction myParseInt(value, dummyPrevious) { // parseInt 参数为字符串和进制数 const parsedValue = parseInt(value, 10); if (isNaN(parsedValue)) { throw new commander.InvalidOptionArgumentError('Not a number.'); } return parsedValue;}```
替代的类是`InvalidArgumentError`,它也可用于自定义命令参数处理。
```jsfunction myParseInt(value, dummyPrevious) { // parseInt 参数为字符串和进制数 const parsedValue = parseInt(value, 10); if (isNaN(parsedValue)) { throw new commander.InvalidArgumentError('Not a number.'); } return parsedValue;}```
原功能自 Commander v8 起不再推荐使用。modified:docs/zh-CN/可变参数的选项.md+10 added-10 removed
6 unmodified lines7 - [方案一:让`--`成为语法的一部分](#%E6%96%B9%E6%A1%88%E4%B8%80%EF%BC%9A%E8%AE%A9%60--%60%E6%88%90%E4%B8%BA%E8%AF%AD%E6%B3%95%E7%9A%84%E4%B8%80%E9%83%A8%E5%88%86)8 - [方案二:把选项放在最后](#%E6%96%B9%E6%A1%88%E4%BA%8C%EF%BC%9A%E6%8A%8A%E9%80%89%E9%A1%B9%E6%94%BE%E5%9C%A8%E6%9C%80%E5%90%8E)9 - [方案三:使用选项替代命令参数](#%E6%96%B9%E6%A1%88%E4%B8%89%EF%BC%9A%E4%BD%BF%E7%94%A8%E9%80%89%E9%A1%B9%E6%9B%BF%E4%BB%A3%E5%91%BD%E4%BB%A4%E5%8F%82%E6%95%B0)10 - [合并短选项,和带有参数的选项](#%E5%90%88%E5%B9%B6%E7%9F%AD%E9%80%89%E9%A1%B9%E5%92%8C%E5%B8%A6%E6%9C%89%E5%8F%82%E6%95%B0%E7%9A%84%E9%80%89%E9%A1%B9)11- - [将短选项视作boolean类型选项合并](#%E5%B0%86%E7%9F%AD%E9%80%89%E9%A1%B9%E8%A7%86%E4%BD%9Cboolean%E7%B1%BB%E5%9E%8B%E9%80%89%E9%A1%B9%E5%90%88%E5%B9%B6)11+ - [将短选项视作 boolean 类型选项合并](#%E5%B0%86%E7%9F%AD%E9%80%89%E9%A1%B9%E8%A7%86%E4%BD%9C-boolean-%E7%B1%BB%E5%9E%8B%E9%80%89%E9%A1%B9%E5%90%88%E5%B9%B6)12 13 有些选项可以接受可变数量的参数:14 15 ```js2 unmodified lines18 .option('--preprocess <file...>') // 至少 1 个参数19 .option('--test [name...]') // 0 或多个参数20 ```21 22-本文中使用的示例代码接受0或1个参数。但相关的讨论对接受更多参数的选项同样适用。22+本文中使用的示例代码接受 0 或 1 个参数。但相关的讨论对接受更多参数的选项同样适用。23 24 关于本文档中使用的术语,参见[术语表](./%E6%9C%AF%E8%AF%AD%E8%A1%A8.md)。25 26 ## 解析中的歧义69 unmodified lines96 ```97 98 ### 方案二:把选项放在最后99 100-Commander 遵循GNU解析命令的惯例,允许选项出现在命令参数之前或者之后,也可以将选项和命令参数相互穿插。100+Commander 遵循 GNU 解析命令的惯例,允许选项出现在命令参数之前或者之后,也可以将选项和命令参数相互穿插。101 因此,通过要求把选项放在最后,命令参数就不会和选项参数相混淆。102 103 ```js104 program.usage('[technique] [options]');35 unmodified lines140 ```141 142 ## 合并短选项和带有参数的选项143 144-多个boolean型的短选项可以合并起来写在同一个`-`号后面,比如`ls -al`。同时,你也可以在其中包括一个接受参数的短选项,此时,任何跟在其后的字符都将被视作这个选项的值。144+多个 boolean 型的短选项可以合并起来写在同一个`-`号后面,比如`ls -al`。同时,你也可以在其中包括一个接受参数的短选项,此时,任何跟在其后的字符都将被视作这个选项的值。145 146 这就是说,默认情况下并不可以把多个带参数的选项合并起来。147 148 ```js12 unmodified lines161 162 ```sh163 $ collect -o 3164 other servings: 3165-$ collect -o3 165+$ collect -o3166 other servings: 3167 $ collect -l -v168 vegan servings: true169 halal servings: true170 $ collect -lv # oops171 halal servings: v172 ```173 174-如果需要使用多个既可用作boolean,又可以接受参数的选项,只能把它们分别声明。174+如果需要使用多个既可用作 boolean,又可以接受参数的选项,只能把它们分别声明。175 176 ```177 $ collect -a -v -l178 any servings: true179 vegan servings: true180 halal servings: true181 ```182 183-### 将短选项视作boolean类型选项合并183+### 将短选项视作 boolean 类型选项合并184 185-在 Commander v5 之前,并不支持合并短选项和值。合并的boolean类型选项会被展开。186-因此,`-avl`将被展开为 `-a -v -l`。185+在 Commander v5 之前,并不支持合并短选项和值。合并的 boolean 类型选项会被展开。186+因此,`-avl`将被展开为`-a -v -l`。187 188-如果您需要后向兼容,或是倾向于在短选项合并的时候把它们视作boolean类型,可以改变此行为:188+如果您需要后向兼容,或是倾向于在短选项合并的时候把它们视作 boolean 类型,可以改变此行为:189 190 ```js191 .combineFlagAndOptionalValue(true) // `-v45` 被视为 `--vegan=45`,这是默认的行为192 .combineFlagAndOptionalValue(false) // `-vl` 被视为 `-v -l`1 unmodified linemodified:docs/zh-CN/术语表.md+2 added-2 removed
2 unmodified lines3456778910112 unmodified lines1415161718182 unmodified lines命令行参数由选项(options)、选项参数(option-arguments)、命令(commands),以及命令参数(command-arguments)组成。
|术语|解释||---|---||选项(options)|`-`后跟单个字母,或`--`后跟单词(或以`-`连接的多个单词),例如`-s`及`--short`||选项(option)|`-`后跟单个字母,或`--`后跟单词(或以`-`连接的多个单词),例如`-s`及`--short`||选项参数(option-argument)|有的选项可以接受一个参数||命令(command)|一个程序或命令可以包含子命令||命令参数(command-argument)|传给命令的参数(不包含选项或选项参数)|
2 unmodified lines```shmy-utility command -o --option option-argument command-argument-1 command-argument-2```
在一些其他资料中,选项有时也称为标志(flags),而命令参数也被称为位置参数(positional arguments)或者操作数(operands)。No newline at end of file在一些其他资料中,选项有时也称为标志(flags),而命令参数也被称为位置参数(positional arguments)或者操作数(operands)。modified:Readme_zh-CN.md+181 added-98 removed
7 unmodified lines8 完整的 [node.js](http://nodejs.org) 命令行解决方案。9 10 使用其他语言阅读:[English](./Readme.md) | 简体中文11 12-Note: this document still describes Commander v7 and has not yet been updated for Commander v8.13-12 - [Commander.js](#commanderjs)13 - [安装](#%e5%ae%89%e8%a3%85)14 - [声明 program 变量](#%e5%a3%b0%e6%98%8e-program-%e5%8f%98%e9%87%8f)15 - [选项](#%e9%80%89%e9%a1%b9)5 unmodified lines21 - [版本选项](#%e7%89%88%e6%9c%ac%e9%80%89%e9%a1%b9)22 - [其他选项配置](#%E5%85%B6%E4%BB%96%E9%80%89%E9%A1%B9%E9%85%8D%E7%BD%AE)23 - [自定义选项处理](#%E8%87%AA%E5%AE%9A%E4%B9%89%E9%80%89%E9%A1%B9%E5%A4%84%E7%90%86)24 - [命令](#%e5%91%bd%e4%bb%a4)27- - [设置命令参数](#%E8%AE%BE%E7%BD%AE%E5%91%BD%E4%BB%A4%E5%8F%82%E6%95%B0)25+ - [命令参数](#%E8%AE%BE%E7%BD%AE%E5%91%BD%E4%BB%A4%E5%8F%82%E6%95%B0)26+ - [其他参数配置](#%E5%85%B6%E4%BB%96%E5%8F%82%E6%95%B0%E9%85%8D%E7%BD%AE)27+ - [自定义参数处理](#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%8F%82%E6%95%B0%E5%A4%84%E7%90%86)28 - [处理函数](#%E5%A4%84%E7%90%86%E5%87%BD%E6%95%B0)29 - [独立的可执行(子)命令](#%E7%8B%AC%E7%AB%8B%E7%9A%84%E5%8F%AF%E6%89%A7%E8%A1%8C%EF%BC%88%E5%AD%90%EF%BC%89%E5%91%BD%E4%BB%A4)30+ - [生命周期钩子](#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90)31 - [自动化帮助信息](#%e8%87%aa%e5%8a%a8%e5%8c%96%e5%b8%ae%e5%8a%a9%e4%bf%a1%e6%81%af)32 - [自定义帮助](#%e8%87%aa%e5%ae%9a%e4%b9%89%e5%b8%ae%e5%8a%a9)33+ - [在出错后展示帮助信息](#%E5%9C%A8%E5%87%BA%E9%94%99%E5%90%8E%E5%B1%95%E7%A4%BA%E5%B8%AE%E5%8A%A9%E4%BF%A1%E6%81%AF)34 - [使用代码展示帮助信息](#%E4%BD%BF%E7%94%A8%E4%BB%A3%E7%A0%81%E5%B1%95%E7%A4%BA%E5%B8%AE%E5%8A%A9%E4%BF%A1%E6%81%AF)35 - [.usage 和 .name](#usage-%e5%92%8c-name)36 - [.helpOption(flags, description)](#helpoptionflags-description)37 - [.addHelpCommand()](#addhelpcommand)4 unmodified lines42 - [解析配置](#%E8%A7%A3%E6%9E%90%E9%85%8D%E7%BD%AE)43 - [作为属性的遗留选项](#%E4%BD%9C%E4%B8%BA%E5%B1%9E%E6%80%A7%E7%9A%84%E9%81%97%E7%95%99%E9%80%89%E9%A1%B9)44 - [TypeScript](#typescript)45 - [createCommand()](#createCommand)44- - [导入到 ES 模块](#%E5%AF%BC%E5%85%A5%E5%88%B0%20ES%20%E6%A8%A1%E5%9D%97)45- - [Node 选项 --harmony](#node-%e9%80%89%e9%a1%b9---harmony)46+ - [Node 选项,如 --harmony](#node-%E9%80%89%E9%A1%B9%EF%BC%8C%E5%A6%82---harmony)47 - [调试子命令](#%e8%b0%83%e8%af%95%e5%ad%90%e5%91%bd%e4%bb%a4)48 - [重写退出和输出](#%E9%87%8D%E5%86%99%E9%80%80%E5%87%BA%E5%92%8C%E8%BE%93%E5%87%BA)49 - [其他文档](#%E5%85%B6%E4%BB%96%E6%96%87%E6%A1%A3)50 - [例子](#%e4%be%8b%e5%ad%90)16 unmodified lines67 const { program } = require('commander');68 program.version('0.0.1');69 ```70 70-如果程序较为复杂,用户需要以多种方式来使用 Commander,如单元测试等。创建本地 Command 对象是一种更好的方式:71+如果程序较为复杂,用户需要以多种方式来使用 Commander,如单元测试等。创建本地`Command`对象是一种更好的方式:72 73 ```js74 const { Command } = require('commander');75 const program = new Command();76 program.version('0.0.1');77 ```78 79+要在 ECMAScript 模块中使用命名导入,可从`commander/esm.mjs`中导入。80+81+```js82+// index.mjs83+import { Command } from 'commander/esm.mjs';84+const program = new Command();85+```86+87+TypeScript 用法:88+89+```ts90+// index.ts91+import { Command } from 'commander';92+const program = new Command();93+```94+95 ## 选项96 80-Commander 使用`.option()` 方法来定义选项,同时可以附加选项的简介。每个选项可以定义一个短选项名称(-后面接单个字符)和一个长选项名称(--后面接一个或多个单词),使用逗号、空格或`|`分隔。97+Commander 使用`.option()`方法来定义选项,同时可以附加选项的简介。每个选项可以定义一个短选项名称(-后面接单个字符)和一个长选项名称(--后面接一个或多个单词),使用逗号、空格或`|`分隔。98 82-选项可以通过在`Command`对象上调用`.opts()`方法来获取。对于多个单词的长选项,使用驼峰法获取,例如`--template-engine`选项通过`program.opts().templateEngine`获取。99+解析后的选项可以通过`Command`对象上的`.opts()`方法获取,同时会被传递给命令处理函数。可以使用`.getOptionValue()`和`.setOptionValue()`操作单个选项的值。100 101+对于多个单词的长选项,选项名会转为驼峰命名法(camel-case),例如`--template-engine`选项可通过`program.opts().templateEngine`获取。102+103 多个短选项可以合并简写,其中最后一个选项可以附加参数。85-例如,`-a -b -p 80` 也可以写为 `-ab -p80` ,甚至进一步简化为 `-abp80`。104+例如,`-a -b -p 80`也可以写为`-ab -p80`,甚至进一步简化为`-abp80`。105 106 `--`可以标记选项的结束,后续的参数均不会被命令解释,可以正常使用。107 108 默认情况下,选项在命令行中的顺序不固定,一个选项可以在其他参数之前或之后指定。19 unmodified lines128 if (options.pizzaType) console.log(`- ${options.pizzaType}`);129 ```130 131 ```bash113-$ pizza-options -d114-{ debug: true, small: undefined, pizzaType: undefined }115-pizza details:132 $ pizza-options -p133 error: option '-p, --pizza-type <type>' argument missing118-$ pizza-options -ds -p vegetarian134+$ pizza-options -d -s -p vegetarian135 { debug: true, small: true, pizzaType: 'vegetarian' }136 pizza details:137 - small pizza size138 - vegetarian27 unmodified lines166 ```167 168 ### 其他的选项类型,取反选项,以及可选参数的选项169 154-可以定义一个以`no-`开头的`boolean`型长选项。在命令行中使用该选项时,会将对应选项的值置为false。当只定义了带`no-`的选项,未定义对应不带`no-`的选项时,该选项的默认值会被置为true。170+可以定义一个以`no-`开头的 boolean 型长选项。在命令行中使用该选项时,会将对应选项的值置为`false`。当只定义了带`no-`的选项,未定义对应不带`no-`的选项时,该选项的默认值会被置为`true`。171 156-如果已经定义了`--foo`,那么再定义`--no-foo`并不会改变它本来的默认值。可以为一个`boolean`类型的选项指定一个默认的布尔值,在命令行里可以重写它的值。172+如果已经定义了`--foo`,那么再定义`--no-foo`并不会改变它本来的默认值。可以为一个 boolean 类型的选项指定一个默认的布尔值,在命令行里可以重写它的值。173 174 示例代码:[options-negatable.js](./examples/options-negatable.js)175 176 ```js19 unmodified lines196 $ pizza-options --no-sauce --no-cheese197 You ordered a pizza with no sauce and no cheese198 ```199 184-选项的参数使用方括号声明表示参数是可选参数(如 `--optional [value]`)。该选项在不带参数时可用作boolean选项,在带有参数时则从参数中得到值。200+选项的参数使用方括号声明表示参数是可选参数(如`--optional [value]`)。该选项在不带参数时可用作 boolean 选项,在带有参数时则从参数中得到值。201 202 示例代码:[options-boolean-or-value.js](./examples/options-boolean-or-value.js)203 204 ```js20 unmodified lines225 关于可能有歧义的用例,请见[可变参数的选项](./docs/zh-CN/%E5%8F%AF%E5%8F%98%E5%8F%82%E6%95%B0%E7%9A%84%E9%80%89%E9%A1%B9.md)。226 227 ### 必填选项228 213-通过`.requiredOption`方法可以设置选项为必填。必填选项要么设有默认值,要么必须在命令行中输入,对应的属性字段在解析时必定会有赋值。该方法其余参数与`.option`一致。229+通过`.requiredOption()`方法可以设置选项为必填。必填选项要么设有默认值,要么必须在命令行中输入,对应的属性字段在解析时必定会有赋值。该方法其余参数与`.option()`一致。230 231 示例代码:[options-required.js](./examples/options-required.js)232 233 ```js9 unmodified lines243 ```244 245 ### 变长参数选项246 231-定义选项时,可以通过使用`...`来设置参数为可变长参数。在命令行中,用户可以输入多个参数,解析后会以数组形式存储在对应属性字段中。在输入下一个选项前(-或--开头),用户输入的指令均会被视作变长参数。与普通参数一样的是,可以通过`--`标记当前命令的结束。247+定义选项时,可以通过使用`...`来设置参数为可变长参数。在命令行中,用户可以输入多个参数,解析后会以数组形式存储在对应属性字段中。在输入下一个选项前(`-`或`--`开头),用户输入的指令均会被视作变长参数。与普通参数一样的是,可以通过`--`标记当前命令的结束。248 249 示例代码:[options-variadic.js](./examples/options-variadic.js)250 251 ```js21 unmodified lines273 关于可能有歧义的用例,请见[可变参数的选项](./docs/zh-CN/%E5%8F%AF%E5%8F%98%E5%8F%82%E6%95%B0%E7%9A%84%E9%80%89%E9%A1%B9.md)。274 275 ### 版本选项276 261-`version`方法可以设置版本,其默认选项为`-V`和`--version`,设置了版本后,命令行会输出当前的版本号。277+`.version()`方法可以设置版本,其默认选项为`-V`和`--version`,设置了版本后,命令行会输出当前的版本号。278 279 ```js280 program.version('0.0.1');281 ```2 unmodified lines284 $ ./examples/pizza -V285 0.0.1286 ```287 272-版本选项也支持自定义设置选项名称,可以在`version`方法里再传递一些参数(长选项名称,描述信息),用法与`option`方法类似。288+版本选项也支持自定义设置选项名称,可以在`.version()`方法里再传递一些参数(长选项名称、描述信息),用法与`.option()`方法类似。289 290 ```bash291 program.version('0.0.1', '-v, --vers', 'output the current version');292 ```1 unmodified line294 ### 其他选项配置295 296 大多数情况下,选项均可通过`.option()`方法添加。但对某些不常见的用例,也可以直接构造`Option`对象,对选项进行更详尽的配置。297 282-示例代码: [options-extra.js](./examples/options-extra.js)298+示例代码:[options-extra.js](./examples/options-extra.js)299 300 ```js301 program302 .addOption(new Option('-s, --secret').hideHelp())15 unmodified lines318 ```319 320 ### 自定义选项处理321 306-选项的参数可以通过自定义函数来处理,该函数接收两个参数:用户新输入的参数值和当前已有的参数值(即上一次调用自定义处理函数后的返回值),返回新的选项参数值。322+选项的参数可以通过自定义函数来处理,该函数接收两个参数,即用户新输入的参数值和当前已有的参数值(即上一次调用自定义处理函数后的返回值),返回新的选项参数值。323 324 自定义函数适用场景包括参数类型转换,参数暂存,或者其他自定义处理的场景。325 310-可以在自定义函数的后面设置选项参数的默认值或初始值(例如参数用`list`暂存时需要设置一个初始空集合)。326+可以在自定义函数的后面设置选项参数的默认值或初始值(例如参数用列表暂存时需要设置一个初始空列表)。327 328 示例代码:[options-custom-processing.js](./examples/options-custom-processing.js)329 330 ```js331 function myParseInt(value, dummyPrevious) {316- // parseInt takes a string and a radix332+ // parseInt 参数为字符串和进制数333 const parsedValue = parseInt(value, 10);334 if (isNaN(parsedValue)) {335 throw new commander.InvalidArgumentError('Not a number.');336 }46 unmodified lines383 ## 命令384 385 通过`.command()`或`.addCommand()`可以配置命令,有两种实现方式:为命令绑定处理函数,或者将命令单独写成一个可执行文件(详述见后文)。子命令支持嵌套([示例代码](./examples/nestedCommands.js))。386 371-`.command()`的第一个参数可以配置命令名称及命令参数,参数支持必选(尖括号表示)、可选(方括号表示)及变长参数(点号表示,如果使用,只能是最后一个参数)。387+`.command()`的第一个参数为命令名称。命令参数可以跟在名称后面,也可以用`.argument()`单独指定。参数可为必选的(尖括号表示)、可选的(方括号表示)或变长参数(点号表示,如果使用,只能是最后一个参数)。388 389 使用`.addCommand()`向`program`增加配置好的子命令。390 391 例如:16 unmodified lines408 409 // 分别装配命令410 // 返回最顶层的命令以供继续添加子命令411 program396- .addCommand(build.makeBuildCommand()); 412+ .addCommand(build.makeBuildCommand());413 ```414 399-使用`.command()`和`addCommand()`来传递配置的选项。当设置`hidden: true`时,该命令不会打印在帮助信息里。当设置`isDefault: true`时,若没有指定其他子命令,则会默认执行这个命令([样例](./examples/defaultCommand.js))。415+使用`.command()`和`addCommand()`来指定选项的相关设置。当设置`hidden: true`时,该命令不会打印在帮助信息里。当设置`isDefault: true`时,若没有指定其他子命令,则会默认执行这个命令([样例](./examples/defaultCommand.js))。416 401-### 设置命令参数417+### 命令参数418 403-通过`.arguments`可以为最顶层命令指定命令参数,对子命令而言,参数都包括在`.command`调用之中了。尖括号(例如`<required>`)意味着必选,而方括号(例如`[optional]`)则代表可选。可以向`.description()`方法传递第二个参数,从而在帮助中展示命令参数的信息。该参数是一个包含了 “命令参数名称:命令参数描述” 键值对的对象。419+如上所述,字命令的参数可以通过`.command()`指定。对于有独立可执行文件的子命令来书,参数只能以这种方法指定。而对其他子命令,参数也可用以下方法。420 405-示例代码:[arguments.js](./examples/arguments.js)421+在`Command`对象上使用`.argument()`来按次序指定命令参数。该方法接受参数名称和参数描述。参数可为必选的(尖括号表示,例如`<required>`)或可选的(方括号表示,例如`[optional]`)。422 423+示例代码:[argument.js](./examples/argument.js)424+425 ```js426 program427 .version('0.1.0')410- .arguments('<username> [password]')411- .description('test command', {412- username: 'user to login',413- password: 'password for user, if required'414- })428+ .argument('<username>', 'user to login')429+ .argument('[password]', 'password for user, if required', 'no password given')430 .action((username, password) => {431 console.log('username:', username);417- console.log('environment:', password || 'no password given');432+ console.log('password:', password);433 });434 ```435 421-在参数名后加上`...`来声明可变参数,且只有最后一个参数支持这种用法,例如436+在参数名后加上`...`来声明可变参数,且只有最后一个参数支持这种用法。可变参数会以数组的形式传递给处理函数。例如:437 438 ```js439 program440 .version('0.1.0')426- .command('rmdir <dirs...>')441+ .command('rmdir')442+ .argument('<dirs...>')443 .action(function (dirs) {444 dirs.forEach((dir) => {445 console.log('rmdir %s', dir);446 });447 });448 ```449 434-可变参数会以数组的形式传递给处理函数。450+有一种便捷方式可以一次性指定多个参数,但不包含参数描述:451 452+```js453+program454+ .arguments('<username> <password>');455+```456+457+#### 其他参数配置458+459+有少数附加功能可以直接构造`Argument`对象,对参数进行更详尽的配置。460+461+示例代码:[arguments-extra.js](./examples/arguments-extra.js)462+463+```js464+program465+ .addArgument(new commander.Argument('<drink-size>', 'drink cup size').choices(['small', 'medium', 'large']))466+ .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute'))467+```468+469+#### 自定义参数处理470+471+选项的参数可以通过自定义函数来处理(与处理选项参数时类似),该函数接收两个参数:用户新输入的参数值和当前已有的参数值(即上一次调用自定义处理函数后的返回值),返回新的命令参数值。472+473+处理后的参数值会传递给命令处理函数,同时可通过`.processedArgs`获取。474+475+可以在自定义函数的后面设置命令参数的默认值或初始值。476+477+示例代码:[arguments-custom-processing.js](./examples/arguments-custom-processing.js)478+479+```js480+program481+ .command('add')482+ .argument('<first>', 'integer argument', myParseInt)483+ .argument('[second]', 'integer argument', myParseInt, 1000)484+ .action((first, second) => {485+ console.log(`${first} + ${second} = ${first + second}`);486+ })487+;488+```489+490 ### 处理函数491 492 命令处理函数的参数,为该命令声明的所有参数,除此之外还会附加两个额外参数:一个是解析出的选项,另一个则是该命令对象自身。493 494 示例代码:[thank.js](./examples/thank.js)495 496 ```js497 program444- .arguments('<name>')498+ .argument('<name>')499 .option('-t, --title <honorific>', 'title to use before name')500 .option('-d, --debug', 'display some debugging')501 .action((name, options, command) => {502 if (options.debug) {16 unmodified lines519 await program.parseAsync(process.argv);520 }521 ```522 469-470-在命令行上使用命令时,选项和命令参数必须是合法的,使用未知的选项,或缺少所需的命令参数,会提示异常。523+使用命令时,所给的选项和命令参数会被验证是否有效。凡是有未知的选项,或缺少所需的命令参数,都会报错。524 如要允许使用未知的选项,可以调用`.allowUnknownOption()`。默认情况下,传入过多的参数并不报错,但也可以通过调用`.allowExcessArguments(false)`来启用过多参数的报错。525 526 ### 独立的可执行(子)命令527 528 当`.command()`带有描述参数时,就意味着使用独立的可执行文件作为子命令。476-Commander 将会尝试在入口脚本(例如 `./examples/pm`)的目录中搜索`program-command`形式的可执行文件,例如`pm-install`, `pm-search`。通过配置选项`executableFile`可以自定义名字。529+Commander 将会尝试在入口脚本(例如`./examples/pm`)的目录中搜索`program-command`形式的可执行文件,例如`pm-install`、`pm-search`。通过配置选项`executableFile`可以自定义名字。530 531 你可以在可执行文件里处理(子)命令的选项,而不必在顶层声明它们。532 533 示例代码:[pm](./examples/pm)10 unmodified lines544 ```545 546 如果该命令需要支持全局安装,请确保有对应的权限,例如`755`。547 548+### 生命周期钩子549+550+可以在命令的生命周期事件上设置回调函数。551+552+示例代码:[hook.js](./examples/hook.js)553+554+```js555+program556+ .option('-t, --trace', 'display trace statements for commands')557+ .hook('preAction', (thisCommand, actionCommand) => {558+ if (thisCommand.opts().trace) {559+ console.log(`About to call action handler for subcommand: ${actionCommand.name()}`);560+ console.log('arguments: %O', actionCommand.args);561+ console.log('options: %o', actionCommand.opts());562+ }563+ });564+```565+566+钩子函数支持`async`,相应的,需要使用`.parseAsync`代替`.parse`。一个事件上可以添加多个钩子。567+568+支持的事件有:569+570+- `preAction`:在本命令或其子命令的处理函数执行前571+- `postAction`:在本命令或其子命令的处理函数执行后572+573+钩子函数的参数为添加上钩子的命令,及实际执行的命令。574+575 ## 自动化帮助信息576 577 帮助信息是 Commander 基于你的程序自动生成的,默认的帮助选项是`-h,--help`。578 11 unmodified lines590 -C, --no-cheese You do not want any cheese591 -h, --help display help for command592 ```593 514-如果你的命令中包含了子命令,会默认添加`help`命令,它可以单独使用,也可以与子命令一起使用来提示更多帮助信息。用法与`shell`程序类似:594+如果你的命令中包含了子命令,会默认添加`help`命令,它可以单独使用,也可以与子命令一起使用来提示更多帮助信息。用法与`shell`程序类似:595 596 ```bash597 shell help598 shell --help5 unmodified lines604 ### 自定义帮助605 606 可以添加额外的帮助信息,与内建的帮助一同展示。607 528-示例代码: [custom-help](./examples/custom-help)608+示例代码:[custom-help](./examples/custom-help)609 610 ```js611 program612 .option('-f, --foo', 'enable some foo');3 unmodified lines616 Example call:617 $ custom-help --help`);618 ```619 540-将会输出以下的帮助信息620+将会输出以下的帮助信息:621 622 ```Text623 Usage: custom-help [options]624 15 unmodified lines640 `beforeAll`和`afterAll`两个参数作用于命令及其所有的子命令。641 642 第二个参数可以是一个字符串,也可以是一个返回字符串的函数。对后者而言,为便于使用,该函数可以接受一个上下文对象,它有如下属性:643 564-- error:boolean值,代表该帮助信息是否由于不当使用而展示565-- command: 代表展示该帮助信息的Command对象644+- `error`:boolean 值,代表该帮助信息是否由于不当使用而展示645+- `command`:代表展示该帮助信息的`Command`对象646 647+### 在出错后展示帮助信息648+649+默认情况下,出现命令用法错误时只会显示错误信息。可以选择在出错后展示完整的帮助或自定义的帮助信息。650+651+```js652+program.showHelpAfterError();653+// 或者654+program.showHelpAfterError('(add --help for additional information)');655+```656+657+```sh658+$ pizza --unknown659+error: unknown option '--unknown'660+(add --help for additional information)661+```662+663 ### 使用代码展示帮助信息664 569-`.help()`:展示帮助信息并退出。可以通过传入`{ error: true }`来将帮助信息作为stderr输出,并以代表错误的状态码退出程序。665+`.help()`:展示帮助信息并退出。可以通过传入`{ error: true }`来让帮助信息从 stderr 输出,并以代表错误的状态码退出程序。666 571-`.outputHelp()`:只展示帮助信息,不退出程序。传入`{ error: true }`可以将帮助信息作为stderr输出。667+`.outputHelp()`:只展示帮助信息,不退出程序。传入`{ error: true }`可以让帮助信息从 stderr 输出。668 573-`.helpInformation()`: 得到字符串形式的内建的帮助信息,以便用于自定义的处理及展示。669+`.helpInformation()`:得到字符串形式的内建的帮助信息,以便用于自定义的处理及展示。670 671 ### .usage 和 .name672 577-通过这两个选项可以修改帮助信息的首行提示,name 属性也可以从参数中推导出来。例如:673+通过这两个选项可以修改帮助信息的首行提示,`name`属性也可以从参数中推导出来。例如:674 675 ```js676 program677 .name("my-command")678 .usage("[global options] command")679 ```680 585-帮助信息会首先输出:681+帮助信息开头如下:682 683 ```Text684 Usage: my-command [global options] command685 ```686 687 ### .helpOption(flags, description)688 593-每一个命令都带有一个默认的帮助选项。可以重写flags和description参数。传入false则会禁用内建的帮助信息。689+每一个命令都带有一个默认的帮助选项。可以重写`flags`和`description`参数。传入`false`则会禁用内建的帮助信息。690 691 ```js692 program693 .helpOption('-e, --HELP', 'read more information');10 unmodified lines704 ```705 706 ### 其他帮助配置707 612-内建帮助信息通过Help类进行格式化。如有需要,可以使用`.configureHelp()`来更改其数据属性和方法,或使用`.createHelp()`来创建子类,从而配置Help类的行为。708+内建帮助信息通过`Help`类进行格式化。如有需要,可以使用`.configureHelp()`来更改其数据属性和方法,或使用`.createHelp()`来创建子类,从而配置`Help`类的行为。709 710 数据属性包括:711 - `helpWidth`:指明帮助信息的宽度。可在单元测试中使用。712 - `sortSubcommands`:以字母序排列子命令713 - `sortOptions`:以字母序排列选项714 619-可以得到可视化的参数列表,选项列表,以及子命令列表。列表的每个元素都具有_term_和_description_属性,并可以对其进行格式化。关于其使用方式,请参考`.formatHelp()`。715+可以得到可视化的参数列表,选项列表,以及子命令列表。列表的每个元素都具有`_term_`和`_description_`属性,并可以对其进行格式化。关于其使用方式,请参考`.formatHelp()`。716 621-示例代码: [configure-help.js](./examples/configure-help.js)717+示例代码:[configure-help.js](./examples/configure-help.js)718 623-```719+```js720 program.configureHelp({721 sortSubcommands: true,626- subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.722+ subcommandTerm: (cmd) => cmd.name() // 显示名称,而非用法723 });724 ```725 726 ## 自定义事件监听1 unmodified line728 监听命令和选项可以执行自定义函数。729 730 ```js731 program.on('option:verbose', function () {636- process.env.VERBOSE = this.verbose;732+ process.env.VERBOSE = this.opts().verbose;733 });734 735 program.on('command:*', function (operands) {736 console.error(`error: unknown command '${operands[0]}'`);10 unmodified lines747 `.parse`的第一个参数是要解析的字符串数组,也可以省略参数而使用`process.argv`。748 749 如果参数遵循与 node 不同的约定,可以在第二个参数中传递`from`选项:750 655-- 'node': 默认值,`argv[0]`是应用,`argv[1]`是要跑的脚本,后续为用户参数;656-- 'electron': `argv[1]`根据 electron 应用是否打包而变化;657-- 'user': 来自用户的所有参数。751+- `node`:默认值,`argv[0]`是应用,`argv[1]`是要跑的脚本,后续为用户参数;752+- `electron`:`argv[1]`根据 electron 应用是否打包而变化;753+- `user`:来自用户的所有参数。754 659-比如:755+例如:756 757 ```js662-program.parse(process.argv); // node663-program.parse();758+program.parse(process.argv); // 指明,按 node 约定759+program.parse(); // 默认,自动识别 electron760 program.parse(['-f', 'filename'], { from: 'user' });761 ```762 763 ### 解析配置764 669-当默认的解析方式无法满足需要,Commander也提供了其他的解析行为。765+当默认的解析方式无法满足需要,Commander 也提供了其他的解析行为。766 767 默认情况下,程序的选项在子命令前后均可被识别。如要只允许选项出现在子命令之前,可以使用`.enablePositionalOptions()`。这样可以在命令和子命令中使用意义不同的同名选项。768 769 示例代码:[positional-options.js](./examples/positional-options.js)7 unmodified lines777 778 默认情况下,选项在命令参数前后均可被识别。如要使选项仅在命令参数前被识别,可以使用`.passThroughOptions()`。这样可以把参数和跟随的选项传递给另一程序,而无需使用`--`来终止选项解析。779 如要在子命令中使用此功能,必须首先启用带顺序的选项解析。780 685-示例代码: [pass-through-options.js](./examples/pass-through-options.js)781+示例代码:[pass-through-options.js](./examples/pass-through-options.js)782 783 当启用此功能时,以下程序中,`--port=80`在第一行中会被解析为程序的选项,而在第二行中则会被解析为一个命令参数:784 785 ```sh6 unmodified lines792 默认情况下,传入过多的命令参数并不会报错。可以使用`.allowExcessArguments(false)`来启用这一检查。793 794 ### 作为属性的遗留选项795 700-在 Commander 7 以前,选项的值是作为属性存储在command对象上的。701-这种处理方式便于实现,但缺点在于,选项可能会与`Command`的已有属性相冲突。通过使用`.storeOptionsAsProperties()`,可以恢复到这种旧的处理方式,并可以不加改动的继续运行遗留代码。796+在 Commander 7 以前,选项的值是作为属性存储在命令对象上的。797+这种处理方式便于实现,但缺点在于,选项可能会与`Command`的已有属性相冲突。通过使用`.storeOptionsAsProperties()`,可以恢复到这种旧的处理方式,并可以不加改动地继续运行遗留代码。798 799 ```js800 program801 .storeOptionsAsProperties()6 unmodified lines808 ```809 810 ### TypeScript811 716-Commander 包里包含了 TypeScript 定义文件。812+如果你使用 ts-node,并有`.ts`文件作为独立可执行文件,那么需要用 node 运行你的程序以使子命令能正确调用,例如:813 718-如果使用`.ts`格式编写命令,则需要通过 node 来执行命令。如:719-814 ```bash815 node -r ts-node/register pm.ts816 ```817 818 ### createCommand()819 726-使用工厂方法可以创建一个`command`,此时不需要使用`new`方法,如820+使用这个工厂方法可以创建新命令,此时不需要使用`new`,如821 822 ```bash823 const { createCommand } = require('commander');824 const program = createCommand();825 ```826 733-`createCommand`是 command 对象的一个方法,可以创建一个新的命令(而非子命令),使用`command()`创建子命令时内部会调用该方法,具体使用方式可参考[custom-command-class.js](./examples/custom-command-class.js)。827+`createCommand`同时也是`Command`对象的一个方法,可以创建一个新的命令(而非子命令),使用`.command()`创建子命令时内部会调用该方法,具体使用方式可参考 [custom-command-class.js](./examples/custom-command-class.js)。828 735-### 导入到 ES 模块829+### Node 选项,如 --harmony830 737-Commander 是一个 CommonJS 包,支持导入到 ES 模块中去。831+要使用`--harmony`等选项有以下两种方式:832 739-```js740-// index.mjs741-import commander from 'commander';742-const program = commander.program;743-const newCommand = new commander.Command();744-```745-746-### Node 选项 --harmony747-748-启用`--harmony`有以下两种方式:749-833 - 在子命令脚本中加上`#!/usr/bin/env node --harmony`。注:Windows 系统不支持;834 - 调用时加上`--harmony`参数,例如`node --harmony examples/pm publish`。`--harmony`选项在开启子进程时仍会保留。835 836 ### 调试子命令837 838 一个可执行的子命令会作为单独的子进程执行。839 757-如果使用 node inspector 的`node -inspect`等命令来[调试](https://nodejs.org/en/docs/guides/debugging-getting-started/)可执行命令,对于生成的子命令,inspector 端口会递增1。840+如果使用 node inspector 的`node -inspect`等命令来[调试](https://nodejs.org/en/docs/guides/debugging-getting-started/)可执行命令,对于生成的子命令,inspector 端口会递增 1。841 842 如果想使用 VSCode 调试,则需要在`launch.json`配置文件里设置`"autoAttachChildProcesses": true`。843 844 ### 重写退出和输出1 unmodified line846 默认情况下,在检测到错误、打印帮助信息或版本信息时 Commander 会调用`process.exit`方法。其默认实现会抛出一个`CommanderError`,可以重写该方法并提供一个回调函数(可选)。847 848 回调函数的参数为`CommanderError`,属性包括 Number 型的`exitCode`、String 型的`code`和`message`。子命令完成调用后会开始异步处理。正常情况下,打印错误信息、帮助信息或版本信息不会被重写影响,因为重写会发生在打印之后。849 767-``` js850+```js851 program.exitOverride();852 853 try {854 program.parse(process.argv);1 unmodified line856 // 自定义处理...857 }858 ```859 777-Commander默认用作命令行应用,其输出写入stdout和stderr。860+Commander 默认用作命令行应用,其输出写入 stdout 和 stderr。861 对于其他应用类型,这一行为可以修改。并且可以修改错误信息的展示方式。862 863 示例代码:[configure-output.js](./examples/configure-output.js)864 865 866 ```js867 function errorColor(str) {785- // 添加ANSI转义字符,以将文本输出为红色868+ // 添加 ANSI 转义字符,以将文本输出为红色869 return `\x1b[31m${str}\x1b[0m`;870 }871 872 program873 .configureOutput({791- // Visibly override write routines as example!874+ // 此处使输出变得容易区分875 writeOut: (str) => process.stdout.write(`[OUT] ${str}`),876 writeErr: (str) => process.stdout.write(`[ERR] ${str}`),794- // Highlight errors in color.877+ // 将错误高亮显示878 outputError: (str, write) => write(errorColor(str))879 });880 ```881 62 unmodified lines944 Examples:945 $ deploy exec sequential946 $ deploy exec async`947 );865- 948+949 program.parse(process.argv);950 ```951 952 更多的示例代码点击[这里](https://github.com/tj/commander.js/tree/master/examples)查看。953 954 ## 支持955 873-当前版本的Commander在LTS版本的Node上完全支持。Node版本应不低于v10。874-(使用更低版本Node的用户建议安装更低版本的Commander。Commander 2.x具有最广泛的支持。)956+当前版本的 Commander 在 LTS 版本的 Node 上完全支持。Node 版本应不低于v12。957+(使用更低版本 Node 的用户建议安装更低版本的 Commander。Commander 2.x 具有最广泛的支持。)958 959 社区支持请访问项目的 [Issues](https://github.com/tj/commander.js/issues)。960 961 ### 企业使用 Commander962 880-现在 Commander 已作为 Tidelift 订阅的一部分。963+作为 Tidelift 订阅的一部分。964 965 Commander 和很多其他包的维护者已与 Tidelift 合作,面向企业提供开源依赖的商业支持与维护。企业可以向相关依赖包的维护者支付一定的费用,帮助企业节省时间,降低风险,改进代码运行情况。[了解更多](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)modified:Readme.md+11 added-11 removed
111 unmodified lines112 113 ### Common option types, boolean and value114 115 The two most used option types are a boolean option, and an option which takes its value116-from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line. 116+from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line.117 118 Example file: [options-common.js](./examples/options-common.js)119 120 ```js304 unmodified lines425 program426 .addCommand(build.makeBuildCommand());427 ```428 429-Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will 429+Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will430 remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other431 subcommand is specified ([example](./examples/defaultCommand.js)).432 433 ### Command-arguments1 unmodified line435 For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This436 is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands437 you can instead use the following method.438 439-To configure a command, you can use `.argument()` to specify each expected command-argument. 439+To configure a command, you can use `.argument()` to specify each expected command-argument.440 You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.441 You can specify a default value for an optional command-argument.442 443 Example file: [argument.js](./examples/argument.js)68 unmodified lines512 513 ### Action handler514 515 The action handler gets passed a parameter for each command-argument you declared, and two additional parameters516-which are the parsed options and the command object itself. 516+which are the parsed options and the command object itself.517 518 Example file: [thank.js](./examples/thank.js)519 520 ```js108 unmodified lines629 ```630 631 ### Custom help632 633-You can add extra text to be displayed along with the built-in help. 633+You can add extra text to be displayed along with the built-in help.634 635 Example file: [custom-help](./examples/custom-help)636 637 ```js25 unmodified lines663 - `before`: display extra information before built-in help664 - `after`: display extra information after built-in help665 - `afterAll`: add to the program for a global footer (epilog)666 667-The positions "beforeAll" and "afterAll" apply to the command and all its subcommands. 667+The positions "beforeAll" and "afterAll" apply to the command and all its subcommands.668 669 The second parameter can be a string, or a function returning a string. The function is passed a context object for your convenience. The properties are:670 671 - error: a boolean for whether the help is being displayed due to a usage error672 - command: the Command which is displaying the help673 674 ### Display help after errors675 676-The default behaviour for usage errors is to just display a short error message. 676+The default behaviour for usage errors is to just display a short error message.677 You can change the behaviour to show the full help or a custom help message after an error.678 679 ```js680 program.showHelpAfterError();65 unmodified lines746 There are methods getting the visible lists of arguments, options, and subcommands. There are methods for formatting the items in the lists, with each item having a _term_ and _description_. Take a look at `.formatHelp()` to see how they are used.747 748 Example file: [configure-help.js](./examples/configure-help.js)749 750-```750+```js751 program.configureHelp({752 sortSubcommands: true,753 subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.754 });53 unmodified lines808 ```809 810 By default options are recognised before and after command-arguments. To only process options that come811 before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another program812-without needing to use `--` to end the option processing. 812+without needing to use `--` to end the option processing.813 To use pass through options in a subcommand, the program needs to enable positional options.814 815 Example file: [pass-through-options.js](./examples/pass-through-options.js)816 8 unmodified lines825 826 By default the argument processing does not display an error for more command-arguments than expected.827 To display an error for excess arguments, use`.allowExcessArguments(false)`.828 829-### Legacy options as properties 829+### Legacy options as properties830 831 Before Commander 7, the option values were stored as properties on the command.832 This was convenient to code but the downside was possible clashes with833 existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.151 unmodified lines985 Examples:986 $ deploy exec sequential987 $ deploy exec async`988 );989- 989+990 program.parse(process.argv);991 ```992 993 More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.13 unmodified lines