Skip to content
Myr

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

5 files+265 added−129 removed

modified:docs/zh-CN/不再推荐使用的功能.md+61 added-8 removed
modified:docs/zh-CN/可变参数的选项.md+10 added-10 removed
6 unmodified lines
7 - [方案一:让`--`成为语法的一部分](#%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)1213有些选项可以接受可变数量的参数:1415```js
2 unmodified lines
18 .option('--preprocess <file...>') // 至少 1 个参数19 .option('--test [name...]') // 0 或多个参数20```2122本文中使用的示例代码接受0或1个参数。但相关的讨论对接受更多参数的选项同样适用。22本文中使用的示例代码接受 0 或 1 个参数。但相关的讨论对接受更多参数的选项同样适用。2324关于本文档中使用的术语,参见[术语表](./%E6%9C%AF%E8%AF%AD%E8%A1%A8.md)。2526## 解析中的歧义
69 unmodified lines
96```9798### 方案二:把选项放在最后99100Commander 遵循GNU解析命令的惯例,允许选项出现在命令参数之前或者之后,也可以将选项和命令参数相互穿插。100Commander 遵循 GNU 解析命令的惯例,允许选项出现在命令参数之前或者之后,也可以将选项和命令参数相互穿插。101因此,通过要求把选项放在最后,命令参数就不会和选项参数相混淆。102103```js104program.usage('[technique] [options]');
35 unmodified lines
140```141142## 合并短选项和带有参数的选项143144多个boolean型的短选项可以合并起来写在同一个`-`号后面,比如`ls -al`。同时,你也可以在其中包括一个接受参数的短选项,此时,任何跟在其后的字符都将被视作这个选项的值。144多个 boolean 型的短选项可以合并起来写在同一个`-`号后面,比如`ls -al`。同时,你也可以在其中包括一个接受参数的短选项,此时,任何跟在其后的字符都将被视作这个选项的值。145146这就是说,默认情况下并不可以把多个带参数的选项合并起来。147148```js
12 unmodified lines
161162```sh163$ collect -o 3164other servings: 3165$ collect -o3 165$ collect -o3166other servings: 3167$ collect -l -v168vegan servings: true169halal servings: true170$ collect -lv # oops171halal servings: v172```173174如果需要使用多个既可用作boolean,又可以接受参数的选项,只能把它们分别声明。174如果需要使用多个既可用作 boolean,又可以接受参数的选项,只能把它们分别声明。175176```177$ collect -a -v -l178any servings: true179vegan servings: true180halal servings: true181```182183### 将短选项视作boolean类型选项合并183### 将短选项视作 boolean 类型选项合并184185在 Commander v5 之前,并不支持合并短选项和值。合并的boolean类型选项会被展开。186因此,`-avl`将被展开为 `-a -v -l`。185在 Commander v5 之前,并不支持合并短选项和值。合并的 boolean 类型选项会被展开。186因此,`-avl`将被展开为`-a -v -l`。187188如果您需要后向兼容,或是倾向于在短选项合并的时候把它们视作boolean类型,可以改变此行为:188如果您需要后向兼容,或是倾向于在短选项合并的时候把它们视作 boolean 类型,可以改变此行为:189190```js191.combineFlagAndOptionalValue(true) // `-v45` 被视为 `--vegan=45`,这是默认的行为192.combineFlagAndOptionalValue(false) // `-vl` 被视为 `-v -l`
1 unmodified line
modified:docs/zh-CN/术语表.md+2 added-2 removed
modified:Readme_zh-CN.md+181 added-98 removed
7 unmodified lines
8完整的 [node.js](http://nodejs.org) 命令行解决方案。910使用其他语言阅读:[English](./Readme.md) | 简体中文1112Note: this document still describes Commander v7 and has not yet been updated for Commander v8.1312- [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 lines
21 - [版本选项](#%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 lines
42 - [解析配置](#%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 lines
67const { program } = require('commander');68program.version('0.0.1');69```7070如果程序较为复杂,用户需要以多种方式来使用 Commander,如单元测试等。创建本地 Command 对象是一种更好的方式:71如果程序较为复杂,用户需要以多种方式来使用 Commander,如单元测试等。创建本地`Command`对象是一种更好的方式:7273```js74const { Command } = require('commander');75const program = new Command();76program.version('0.0.1');77```7879要在 ECMAScript 模块中使用命名导入,可从`commander/esm.mjs`中导入。8081```js82// index.mjs83import { Command } from 'commander/esm.mjs';84const program = new Command();85```8687TypeScript 用法:8889```ts90// index.ts91import { Command } from 'commander';92const program = new Command();93```9495## 选项9680Commander 使用`.option()` 方法来定义选项,同时可以附加选项的简介。每个选项可以定义一个短选项名称(-后面接单个字符)和一个长选项名称(--后面接一个或多个单词),使用逗号、空格或`|`分隔。97Commander 使用`.option()`方法来定义选项,同时可以附加选项的简介。每个选项可以定义一个短选项名称(-后面接单个字符)和一个长选项名称(--后面接一个或多个单词),使用逗号、空格或`|`分隔。9882选项可以通过在`Command`对象上调用`.opts()`方法来获取。对于多个单词的长选项,使用驼峰法获取,例如`--template-engine`选项通过`program.opts().templateEngine`获取。99解析后的选项可以通过`Command`对象上的`.opts()`方法获取,同时会被传递给命令处理函数。可以使用`.getOptionValue()`和`.setOptionValue()`操作单个选项的值。100101对于多个单词的长选项,选项名会转为驼峰命名法(camel-case),例如`--template-engine`选项可通过`program.opts().templateEngine`获取。102103多个短选项可以合并简写,其中最后一个选项可以附加参数。85例如,`-a -b -p 80` 也可以写为 `-ab -p80` ,甚至进一步简化为 `-abp80`。104例如,`-a -b -p 80`也可以写为`-ab -p80`,甚至进一步简化为`-abp80`。105106`--`可以标记选项的结束,后续的参数均不会被命令解释,可以正常使用。107108默认情况下,选项在命令行中的顺序不固定,一个选项可以在其他参数之前或之后指定。
19 unmodified lines
128if (options.pizzaType) console.log(`- ${options.pizzaType}`);129```130131```bash113$ pizza-options -d114{ debug: true, small: undefined, pizzaType: undefined }115pizza details:132$ pizza-options -p133error: option '-p, --pizza-type <type>' argument missing118$ pizza-options -ds -p vegetarian134$ pizza-options -d -s -p vegetarian135{ debug: true, small: true, pizzaType: 'vegetarian' }136pizza details:137- small pizza size138- vegetarian
27 unmodified lines
166```167168### 其他的选项类型,取反选项,以及可选参数的选项169154可以定义一个以`no-`开头的`boolean`型长选项。在命令行中使用该选项时,会将对应选项的值置为false。当只定义了带`no-`的选项,未定义对应不带`no-`的选项时,该选项的默认值会被置为true。170可以定义一个以`no-`开头的 boolean 型长选项。在命令行中使用该选项时,会将对应选项的值置为`false`。当只定义了带`no-`的选项,未定义对应不带`no-`的选项时,该选项的默认值会被置为`true`。171156如果已经定义了`--foo`,那么再定义`--no-foo`并不会改变它本来的默认值。可以为一个`boolean`类型的选项指定一个默认的布尔值,在命令行里可以重写它的值。172如果已经定义了`--foo`,那么再定义`--no-foo`并不会改变它本来的默认值。可以为一个 boolean 类型的选项指定一个默认的布尔值,在命令行里可以重写它的值。173174示例代码:[options-negatable.js](./examples/options-negatable.js)175176```js
19 unmodified lines
196$ pizza-options --no-sauce --no-cheese197You ordered a pizza with no sauce and no cheese198```199184选项的参数使用方括号声明表示参数是可选参数(如 `--optional [value]`)。该选项在不带参数时可用作boolean选项,在带有参数时则从参数中得到值。200选项的参数使用方括号声明表示参数是可选参数(如`--optional [value]`)。该选项在不带参数时可用作 boolean 选项,在带有参数时则从参数中得到值。201202示例代码:[options-boolean-or-value.js](./examples/options-boolean-or-value.js)203204```js
20 unmodified lines
225关于可能有歧义的用例,请见[可变参数的选项](./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)。226227### 必填选项228213通过`.requiredOption`方法可以设置选项为必填。必填选项要么设有默认值,要么必须在命令行中输入,对应的属性字段在解析时必定会有赋值。该方法其余参数与`.option`一致。229通过`.requiredOption()`方法可以设置选项为必填。必填选项要么设有默认值,要么必须在命令行中输入,对应的属性字段在解析时必定会有赋值。该方法其余参数与`.option()`一致。230231示例代码:[options-required.js](./examples/options-required.js)232233```js
9 unmodified lines
243```244245### 变长参数选项246231定义选项时,可以通过使用`...`来设置参数为可变长参数。在命令行中,用户可以输入多个参数,解析后会以数组形式存储在对应属性字段中。在输入下一个选项前(-或--开头),用户输入的指令均会被视作变长参数。与普通参数一样的是,可以通过`--`标记当前命令的结束。247定义选项时,可以通过使用`...`来设置参数为可变长参数。在命令行中,用户可以输入多个参数,解析后会以数组形式存储在对应属性字段中。在输入下一个选项前(`-`或`--`开头),用户输入的指令均会被视作变长参数。与普通参数一样的是,可以通过`--`标记当前命令的结束。248249示例代码:[options-variadic.js](./examples/options-variadic.js)250251```js
21 unmodified lines
273关于可能有歧义的用例,请见[可变参数的选项](./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)。274275### 版本选项276261`version`方法可以设置版本,其默认选项为`-V`和`--version`,设置了版本后,命令行会输出当前的版本号。277`.version()`方法可以设置版本,其默认选项为`-V`和`--version`,设置了版本后,命令行会输出当前的版本号。278279```js280program.version('0.0.1');281```
2 unmodified lines
284$ ./examples/pizza -V2850.0.1286```287272版本选项也支持自定义设置选项名称,可以在`version`方法里再传递一些参数(长选项名称,描述信息),用法与`option`方法类似。288版本选项也支持自定义设置选项名称,可以在`.version()`方法里再传递一些参数(长选项名称、描述信息),用法与`.option()`方法类似。289290```bash291program.version('0.0.1', '-v, --vers', 'output the current version');292```
1 unmodified line
294### 其他选项配置295296大多数情况下,选项均可通过`.option()`方法添加。但对某些不常见的用例,也可以直接构造`Option`对象,对选项进行更详尽的配置。297282示例代码: [options-extra.js](./examples/options-extra.js)298示例代码:[options-extra.js](./examples/options-extra.js)299300```js301program302 .addOption(new Option('-s, --secret').hideHelp())
15 unmodified lines
318```319320### 自定义选项处理321306选项的参数可以通过自定义函数来处理,该函数接收两个参数:用户新输入的参数值和当前已有的参数值(即上一次调用自定义处理函数后的返回值),返回新的选项参数值。322选项的参数可以通过自定义函数来处理,该函数接收两个参数,即用户新输入的参数值和当前已有的参数值(即上一次调用自定义处理函数后的返回值),返回新的选项参数值。323324自定义函数适用场景包括参数类型转换,参数暂存,或者其他自定义处理的场景。325310可以在自定义函数的后面设置选项参数的默认值或初始值(例如参数用`list`暂存时需要设置一个初始空集合)。326可以在自定义函数的后面设置选项参数的默认值或初始值(例如参数用列表暂存时需要设置一个初始空列表)。327328示例代码:[options-custom-processing.js](./examples/options-custom-processing.js)329330```js331function 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 lines
383## 命令384385通过`.command()`或`.addCommand()`可以配置命令,有两种实现方式:为命令绑定处理函数,或者将命令单独写成一个可执行文件(详述见后文)。子命令支持嵌套([示例代码](./examples/nestedCommands.js))。386371`.command()`的第一个参数可以配置命令名称及命令参数,参数支持必选(尖括号表示)、可选(方括号表示)及变长参数(点号表示,如果使用,只能是最后一个参数)。387`.command()`的第一个参数为命令名称。命令参数可以跟在名称后面,也可以用`.argument()`单独指定。参数可为必选的(尖括号表示)、可选的(方括号表示)或变长参数(点号表示,如果使用,只能是最后一个参数)。388389使用`.addCommand()`向`program`增加配置好的子命令。390391例如:
16 unmodified lines
408409// 分别装配命令410// 返回最顶层的命令以供继续添加子命令411program396 .addCommand(build.makeBuildCommand()); 412 .addCommand(build.makeBuildCommand());413```414399使用`.command()`和`addCommand()`来传递配置的选项。当设置`hidden: true`时,该命令不会打印在帮助信息里。当设置`isDefault: true`时,若没有指定其他子命令,则会默认执行这个命令([样例](./examples/defaultCommand.js))。415使用`.command()`和`addCommand()`来指定选项的相关设置。当设置`hidden: true`时,该命令不会打印在帮助信息里。当设置`isDefault: true`时,若没有指定其他子命令,则会默认执行这个命令([样例](./examples/defaultCommand.js))。416401### 设置命令参数417### 命令参数418403通过`.arguments`可以为最顶层命令指定命令参数,对子命令而言,参数都包括在`.command`调用之中了。尖括号(例如`<required>`)意味着必选,而方括号(例如`[optional]`)则代表可选。可以向`.description()`方法传递第二个参数,从而在帮助中展示命令参数的信息。该参数是一个包含了 “命令参数名称:命令参数描述” 键值对的对象。419如上所述,字命令的参数可以通过`.command()`指定。对于有独立可执行文件的子命令来书,参数只能以这种方法指定。而对其他子命令,参数也可用以下方法。420405示例代码:[arguments.js](./examples/arguments.js)421在`Command`对象上使用`.argument()`来按次序指定命令参数。该方法接受参数名称和参数描述。参数可为必选的(尖括号表示,例如`<required>`)或可选的(方括号表示,例如`[optional]`)。422423示例代码:[argument.js](./examples/argument.js)424425```js426program427 .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```435421在参数名后加上`...`来声明可变参数,且只有最后一个参数支持这种用法,例如436在参数名后加上`...`来声明可变参数,且只有最后一个参数支持这种用法。可变参数会以数组的形式传递给处理函数。例如:437438```js439program440 .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```449434可变参数会以数组的形式传递给处理函数。450有一种便捷方式可以一次性指定多个参数,但不包含参数描述:451452```js453program454 .arguments('<username> <password>');455```456457#### 其他参数配置458459有少数附加功能可以直接构造`Argument`对象,对参数进行更详尽的配置。460461示例代码:[arguments-extra.js](./examples/arguments-extra.js)462463```js464program465 .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```468469#### 自定义参数处理470471选项的参数可以通过自定义函数来处理(与处理选项参数时类似),该函数接收两个参数:用户新输入的参数值和当前已有的参数值(即上一次调用自定义处理函数后的返回值),返回新的命令参数值。472473处理后的参数值会传递给命令处理函数,同时可通过`.processedArgs`获取。474475可以在自定义函数的后面设置命令参数的默认值或初始值。476477示例代码:[arguments-custom-processing.js](./examples/arguments-custom-processing.js)478479```js480program481 .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```489490### 处理函数491492命令处理函数的参数,为该命令声明的所有参数,除此之外还会附加两个额外参数:一个是解析出的选项,另一个则是该命令对象自身。493494示例代码:[thank.js](./examples/thank.js)495496```js497program444 .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 lines
519 await program.parseAsync(process.argv);520}521```522469470在命令行上使用命令时,选项和命令参数必须是合法的,使用未知的选项,或缺少所需的命令参数,会提示异常。523使用命令时,所给的选项和命令参数会被验证是否有效。凡是有未知的选项,或缺少所需的命令参数,都会报错。524如要允许使用未知的选项,可以调用`.allowUnknownOption()`。默认情况下,传入过多的参数并不报错,但也可以通过调用`.allowExcessArguments(false)`来启用过多参数的报错。525526### 独立的可执行(子)命令527528当`.command()`带有描述参数时,就意味着使用独立的可执行文件作为子命令。476Commander 将会尝试在入口脚本(例如 `./examples/pm`)的目录中搜索`program-command`形式的可执行文件,例如`pm-install`, `pm-search`。通过配置选项`executableFile`可以自定义名字。529Commander 将会尝试在入口脚本(例如`./examples/pm`)的目录中搜索`program-command`形式的可执行文件,例如`pm-install`、`pm-search`。通过配置选项`executableFile`可以自定义名字。530531你可以在可执行文件里处理(子)命令的选项,而不必在顶层声明它们。532533示例代码:[pm](./examples/pm)
10 unmodified lines
544```545546如果该命令需要支持全局安装,请确保有对应的权限,例如`755`。547548### 生命周期钩子549550可以在命令的生命周期事件上设置回调函数。551552示例代码:[hook.js](./examples/hook.js)553554```js555program556 .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```565566钩子函数支持`async`,相应的,需要使用`.parseAsync`代替`.parse`。一个事件上可以添加多个钩子。567568支持的事件有:569570- `preAction`:在本命令或其子命令的处理函数执行前571- `postAction`:在本命令或其子命令的处理函数执行后572573钩子函数的参数为添加上钩子的命令,及实际执行的命令。574575## 自动化帮助信息576577帮助信息是 Commander 基于你的程序自动生成的,默认的帮助选项是`-h,--help`。578
11 unmodified lines
590 -C, --no-cheese You do not want any cheese591 -h, --help display help for command592```593514如果你的命令中包含了子命令,会默认添加`help`命令,它可以单独使用,也可以与子命令一起使用来提示更多帮助信息。用法与`shell`程序类似:594如果你的命令中包含了子命令,会默认添加`help`命令,它可以单独使用,也可以与子命令一起使用来提示更多帮助信息。用法与`shell`程序类似:595596```bash597shell help598shell --help
5 unmodified lines
604### 自定义帮助605606可以添加额外的帮助信息,与内建的帮助一同展示。607528示例代码: [custom-help](./examples/custom-help)608示例代码:[custom-help](./examples/custom-help)609610```js611program612 .option('-f, --foo', 'enable some foo');
3 unmodified lines
616Example call:617 $ custom-help --help`);618```619540将会输出以下的帮助信息620将会输出以下的帮助信息:621622```Text623Usage: custom-help [options]624
15 unmodified lines
640`beforeAll`和`afterAll`两个参数作用于命令及其所有的子命令。641642第二个参数可以是一个字符串,也可以是一个返回字符串的函数。对后者而言,为便于使用,该函数可以接受一个上下文对象,它有如下属性:643564- error:boolean值,代表该帮助信息是否由于不当使用而展示565- command: 代表展示该帮助信息的Command对象644- `error`:boolean 值,代表该帮助信息是否由于不当使用而展示645- `command`:代表展示该帮助信息的`Command`对象646647### 在出错后展示帮助信息648649默认情况下,出现命令用法错误时只会显示错误信息。可以选择在出错后展示完整的帮助或自定义的帮助信息。650651```js652program.showHelpAfterError();653// 或者654program.showHelpAfterError('(add --help for additional information)');655```656657```sh658$ pizza --unknown659error: unknown option '--unknown'660(add --help for additional information)661```662663### 使用代码展示帮助信息664569`.help()`:展示帮助信息并退出。可以通过传入`{ error: true }`来将帮助信息作为stderr输出,并以代表错误的状态码退出程序。665`.help()`:展示帮助信息并退出。可以通过传入`{ error: true }`来让帮助信息从 stderr 输出,并以代表错误的状态码退出程序。666571`.outputHelp()`:只展示帮助信息,不退出程序。传入`{ error: true }`可以将帮助信息作为stderr输出。667`.outputHelp()`:只展示帮助信息,不退出程序。传入`{ error: true }`可以让帮助信息从 stderr 输出。668573`.helpInformation()`: 得到字符串形式的内建的帮助信息,以便用于自定义的处理及展示。669`.helpInformation()`:得到字符串形式的内建的帮助信息,以便用于自定义的处理及展示。670671### .usage 和 .name672577通过这两个选项可以修改帮助信息的首行提示,name 属性也可以从参数中推导出来。例如:673通过这两个选项可以修改帮助信息的首行提示,`name`属性也可以从参数中推导出来。例如:674675```js676program677 .name("my-command")678 .usage("[global options] command")679```680585帮助信息会首先输出:681帮助信息开头如下:682683```Text684Usage: my-command [global options] command685```686687### .helpOption(flags, description)688593每一个命令都带有一个默认的帮助选项。可以重写flags和description参数。传入false则会禁用内建的帮助信息。689每一个命令都带有一个默认的帮助选项。可以重写`flags`和`description`参数。传入`false`则会禁用内建的帮助信息。690691```js692program693 .helpOption('-e, --HELP', 'read more information');
10 unmodified lines
704```705706### 其他帮助配置707612内建帮助信息通过Help类进行格式化。如有需要,可以使用`.configureHelp()`来更改其数据属性和方法,或使用`.createHelp()`来创建子类,从而配置Help类的行为。708内建帮助信息通过`Help`类进行格式化。如有需要,可以使用`.configureHelp()`来更改其数据属性和方法,或使用`.createHelp()`来创建子类,从而配置`Help`类的行为。709710数据属性包括:711- `helpWidth`:指明帮助信息的宽度。可在单元测试中使用。712- `sortSubcommands`:以字母序排列子命令713- `sortOptions`:以字母序排列选项714619可以得到可视化的参数列表,选项列表,以及子命令列表。列表的每个元素都具有_term_和_description_属性,并可以对其进行格式化。关于其使用方式,请参考`.formatHelp()`。715可以得到可视化的参数列表,选项列表,以及子命令列表。列表的每个元素都具有`_term_`和`_description_`属性,并可以对其进行格式化。关于其使用方式,请参考`.formatHelp()`。716621示例代码: [configure-help.js](./examples/configure-help.js)717示例代码:[configure-help.js](./examples/configure-help.js)718623```719```js720program.configureHelp({721 sortSubcommands: true,626 subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.722 subcommandTerm: (cmd) => cmd.name() // 显示名称,而非用法723});724```725726## 自定义事件监听
1 unmodified line
728监听命令和选项可以执行自定义函数。729730```js731program.on('option:verbose', function () {636 process.env.VERBOSE = this.verbose;732 process.env.VERBOSE = this.opts().verbose;733});734735program.on('command:*', function (operands) {736 console.error(`error: unknown command '${operands[0]}'`);
10 unmodified lines
747`.parse`的第一个参数是要解析的字符串数组,也可以省略参数而使用`process.argv`。748749如果参数遵循与 node 不同的约定,可以在第二个参数中传递`from`选项:750655- '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`:来自用户的所有参数。754659比如:755例如:756757```js662program.parse(process.argv); // node663program.parse();758program.parse(process.argv); // 指明,按 node 约定759program.parse(); // 默认,自动识别 electron760program.parse(['-f', 'filename'], { from: 'user' });761```762763### 解析配置764669当默认的解析方式无法满足需要,Commander也提供了其他的解析行为。765当默认的解析方式无法满足需要,Commander 也提供了其他的解析行为。766767默认情况下,程序的选项在子命令前后均可被识别。如要只允许选项出现在子命令之前,可以使用`.enablePositionalOptions()`。这样可以在命令和子命令中使用意义不同的同名选项。768769示例代码:[positional-options.js](./examples/positional-options.js)
7 unmodified lines
777778默认情况下,选项在命令参数前后均可被识别。如要使选项仅在命令参数前被识别,可以使用`.passThroughOptions()`。这样可以把参数和跟随的选项传递给另一程序,而无需使用`--`来终止选项解析。779如要在子命令中使用此功能,必须首先启用带顺序的选项解析。780685示例代码: [pass-through-options.js](./examples/pass-through-options.js)781示例代码:[pass-through-options.js](./examples/pass-through-options.js)782783当启用此功能时,以下程序中,`--port=80`在第一行中会被解析为程序的选项,而在第二行中则会被解析为一个命令参数:784785```sh
6 unmodified lines
792默认情况下,传入过多的命令参数并不会报错。可以使用`.allowExcessArguments(false)`来启用这一检查。793794### 作为属性的遗留选项795700在 Commander 7 以前,选项的值是作为属性存储在command对象上的。701这种处理方式便于实现,但缺点在于,选项可能会与`Command`的已有属性相冲突。通过使用`.storeOptionsAsProperties()`,可以恢复到这种旧的处理方式,并可以不加改动的继续运行遗留代码。796在 Commander 7 以前,选项的值是作为属性存储在命令对象上的。797这种处理方式便于实现,但缺点在于,选项可能会与`Command`的已有属性相冲突。通过使用`.storeOptionsAsProperties()`,可以恢复到这种旧的处理方式,并可以不加改动地继续运行遗留代码。798799```js800program801 .storeOptionsAsProperties()
6 unmodified lines
808```809810### TypeScript811716Commander 包里包含了 TypeScript 定义文件。812如果你使用 ts-node,并有`.ts`文件作为独立可执行文件,那么需要用 node 运行你的程序以使子命令能正确调用,例如:813718如果使用`.ts`格式编写命令,则需要通过 node 来执行命令。如:719814```bash815node -r ts-node/register pm.ts816```817818### createCommand()819726使用工厂方法可以创建一个`command`,此时不需要使用`new`方法,如820使用这个工厂方法可以创建新命令,此时不需要使用`new`,如821822```bash823const { createCommand } = require('commander');824const program = createCommand();825```826733`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)。828735### 导入到 ES 模块829### Node 选项,如 --harmony830737Commander 是一个 CommonJS 包,支持导入到 ES 模块中去。831要使用`--harmony`等选项有以下两种方式:832739```js740// index.mjs741import commander from 'commander';742const program = commander.program;743const newCommand = new commander.Command();744```745746### Node 选项 --harmony747748启用`--harmony`有以下两种方式:749833- 在子命令脚本中加上`#!/usr/bin/env node --harmony`。注:Windows 系统不支持;834- 调用时加上`--harmony`参数,例如`node --harmony examples/pm publish`。`--harmony`选项在开启子进程时仍会保留。835836### 调试子命令837838一个可执行的子命令会作为单独的子进程执行。839757如果使用 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。841842如果想使用 VSCode 调试,则需要在`launch.json`配置文件里设置`"autoAttachChildProcesses": true`。843844### 重写退出和输出
1 unmodified line
846默认情况下,在检测到错误、打印帮助信息或版本信息时 Commander 会调用`process.exit`方法。其默认实现会抛出一个`CommanderError`,可以重写该方法并提供一个回调函数(可选)。847848回调函数的参数为`CommanderError`,属性包括 Number 型的`exitCode`、String 型的`code`和`message`。子命令完成调用后会开始异步处理。正常情况下,打印错误信息、帮助信息或版本信息不会被重写影响,因为重写会发生在打印之后。849767``` js850```js851program.exitOverride();852853try {854 program.parse(process.argv);
1 unmodified line
856 // 自定义处理...857}858```859777Commander默认用作命令行应用,其输出写入stdout和stderr。860Commander 默认用作命令行应用,其输出写入 stdout 和 stderr。861对于其他应用类型,这一行为可以修改。并且可以修改错误信息的展示方式。862863示例代码:[configure-output.js](./examples/configure-output.js)864865866```js867function errorColor(str) {785 // 添加ANSI转义字符,以将文本输出为红色868 // 添加 ANSI 转义字符,以将文本输出为红色869 return `\x1b[31m${str}\x1b[0m`;870}871872program873 .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 lines
944Examples:945 $ deploy exec sequential946 $ deploy exec async`947 );865 948949program.parse(process.argv);950```951952更多的示例代码点击[这里](https://github.com/tj/commander.js/tree/master/examples)查看。953954## 支持955873当前版本的Commander在LTS版本的Node上完全支持。Node版本应不低于v10。874(使用更低版本Node的用户建议安装更低版本的Commander。Commander 2.x具有最广泛的支持。)956当前版本的 Commander 在 LTS 版本的 Node 上完全支持。Node 版本应不低于v12。957(使用更低版本 Node 的用户建议安装更低版本的 Commander。Commander 2.x 具有最广泛的支持。)958959社区支持请访问项目的 [Issues](https://github.com/tj/commander.js/issues)。960961### 企业使用 Commander962880现在 Commander 已作为 Tidelift 订阅的一部分。963作为 Tidelift 订阅的一部分。964965Commander 和很多其他包的维护者已与 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 lines
112113### Common option types, boolean and value114115The two most used option types are a boolean option, and an option which takes its value116from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line. 116from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line.117118Example file: [options-common.js](./examples/options-common.js)119120```js
304 unmodified lines
425program426 .addCommand(build.makeBuildCommand());427```428429Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will 429Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will430remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other431subcommand is specified ([example](./examples/defaultCommand.js)).432433### Command-arguments
1 unmodified line
435For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This436is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands437you can instead use the following method.438439To configure a command, you can use `.argument()` to specify each expected command-argument. 439To configure a command, you can use `.argument()` to specify each expected command-argument.440You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.441You can specify a default value for an optional command-argument.442443Example file: [argument.js](./examples/argument.js)
68 unmodified lines
512513### Action handler514515The action handler gets passed a parameter for each command-argument you declared, and two additional parameters516which are the parsed options and the command object itself. 516which are the parsed options and the command object itself.517518Example file: [thank.js](./examples/thank.js)519520```js
108 unmodified lines
629```630631### Custom help632633You can add extra text to be displayed along with the built-in help. 633You can add extra text to be displayed along with the built-in help.634635Example file: [custom-help](./examples/custom-help)636637```js
25 unmodified lines
663- `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)666667The positions "beforeAll" and "afterAll" apply to the command and all its subcommands. 667The positions "beforeAll" and "afterAll" apply to the command and all its subcommands.668669The 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:670671- error: a boolean for whether the help is being displayed due to a usage error672- command: the Command which is displaying the help673674### Display help after errors675676The default behaviour for usage errors is to just display a short error message. 676The default behaviour for usage errors is to just display a short error message.677You can change the behaviour to show the full help or a custom help message after an error.678679```js680program.showHelpAfterError();
65 unmodified lines
746There 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.747748Example file: [configure-help.js](./examples/configure-help.js)749750```750```js751program.configureHelp({752 sortSubcommands: true,753 subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.754});
53 unmodified lines
808```809810By default options are recognised before and after command-arguments. To only process options that come811before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another program812without needing to use `--` to end the option processing. 812without needing to use `--` to end the option processing.813To use pass through options in a subcommand, the program needs to enable positional options.814815Example file: [pass-through-options.js](./examples/pass-through-options.js)816
8 unmodified lines
825826By default the argument processing does not display an error for more command-arguments than expected.827To display an error for excess arguments, use`.allowExcessArguments(false)`.828829### Legacy options as properties 829### Legacy options as properties830831Before Commander 7, the option values were stored as properties on the command.832This was convenient to code but the downside was possible clashes with833existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.
151 unmodified lines
985Examples:986 $ deploy exec sequential987 $ deploy exec async`988 );989 989990program.parse(process.argv);991```992993More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
13 unmodified lines