Skip to content
Myr

update chinese README

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by banli17 · committed by banli17 · parent 3598303 · Browse files · 1 file+198 added−48 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+198 added−48 removed

  • other:+198 added−48 removed

1 file+198 added−48 removed

modified:Readme_zh-CN.md+198 added-48 removed
11 unmodified lines
12## 安装1314 $ npm install commander1516## 参数解析17 `.option()` 方法用来定义带选项的 commander,同时也作为这些选项的文档。下面的例子会解析来自 `process.argv` 指定的参数和选项,没有匹配任何选项的参数将会放到 `program.args` 数组中。16## 声明program变量1718Commander为了方便快速编程导出了一个全局对象。为简洁起见,本README中的示例中使用了它。1920```js20#!/usr/bin/env node21const program = require('commander');22program.version('0.0.1');23```2422/**23 * Module dependencies.24 */25对于可能以多种方式使用commander的大型程序,包括单元测试,最好创建一个本地Command对象来使用。2627```js26var program = require('commander');28const commander = require('commander');29const program = new commander.Command();30program.version('0.0.1');31```3233## 选项3435`.option()` 方法用来定义带选项的 commander,同时也用于这些选项的文档。每个选项可以有一个短标识(单个字符)和一个长名字,它们之间用逗号或空格分开。3637 选项会被放到 Commander 对象的属性上,多词选项如"--template-engine"会被转为驼峰法`program.templateEngine`。多个短标识可以组合为一个参数,如`-a -b -c`等价于`-abc`。3839### 常用选项类型,boolean和值4041最常用的两个选项类型是boolean(选项后面不跟值)和选项跟一个值(使用尖括号声明)。除非在命令行中指定,否则两者都是`undefined`。4243 ```js44const program = require('commander');4546program29 .version('0.0.1')30 .option('-p, --peppers', 'Add peppers')31 .option('-P, --pineapple', 'Add pineapple')32 .option('-b, --bbq-sauce', 'Add bbq sauce')33 .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')47 .option('-d, --debug', 'output extra debugging')48 .option('-s, --small', 'small pizza size')49 .option('-p, --pizza-type <type>', 'flavour of pizza');5051program.parse(process.argv);5253if (program.debug) console.log(program.opts());54console.log('pizza details:');55if (program.small) console.log('- small pizza size');56if (program.pizzaType) console.log(`- ${program.pizzaType}`);57 ```5859```60$ pizza-options -d61{ debug: true, small: undefined, pizzaType: undefined }62pizza details:63$ pizza-options -p64error: option `-p, --pizza-type <type>' argument missing65$ pizza-options -ds -p vegetarian66{ debug: true, small: true, pizzaType: 'vegetarian' }67pizza details:68- small pizza size69- vegetarian70$ pizza-options --pizza-type=cheese71pizza details:72- cheese73```7475`program.parse(arguments)`会处理参数,没有被使用的选项会被存放在`program.args`数组中。7677### 默认选项值7879可以为选项设置一个默认值。8081```js82const program = require('commander');8384program85 .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');8687program.parse(process.argv);8889console.log(`cheese: ${program.cheese}`);90```9192```93$ pizza-options94cheese: blue95$ pizza-options --cheese stilton96cheese: stilton97```9899### 其他选项类型,可忽略的布尔值和标志值100101选项的值为 boolean 类型时,可以在其长名字前加`no-`使默认值为true,如果传了这个选项则值为false。102103```js104const program = require('commander');105106program107 .option('-n, --no-sauce', 'Remove sauce')108 .parse(process.argv);10936console.log('you ordered a pizza with:');37if (program.peppers) console.log(' - peppers');38if (program.pineapple) console.log(' - pineapple');39if (program.bbqSauce) console.log(' - bbq');40console.log(' - %s cheese', program.cheese);110if (program.sauce) console.log('you ordered a pizza with sauce');111else console.log('you ordered a pizza without sauce');112```11343 短标志可以作为单独的参数传递。像 `-abc` 等于 `-a -b -c`。多词组成的选项,像“--template-engine”会变成 `program.templateEngine` 等。114```115$ pizza-options116you ordered a pizza with sauce117$ pizza-options --sauce118error: unknown option `--sauce'119$ pizza-options --no-sauce120you ordered a pizza without sauce121```122123您可以指定一个用作标志的选项,它可以接受值(使用方括号声明,即传值不是必须的)。12446## 强制多态125```js126const program = require('commander');127128program129 .option('-c, --cheese [type]', 'Add cheese with optional type');130131program.parse(process.argv);132133if (program.cheese === undefined) console.log('no cheese');134else if (program.cheese === true) console.log('add cheese');135else console.log(`add cheese type ${program.cheese}`);136```137138## 自定义选项处理139140你可以指定一个函数来处理选项的值,接收两个参数:用户传入的值、上一个值(previous value),它会返回新的选项值。141142你可以将选项值强制转换为所需类型,或累积值,或完全自定义处理。143144你可以在函数后面指定选项的默认或初始值。145146```js49function range(val) {50 return val.split('..').map(Number);147const program = require('commander');148149function myParseInt(value, dummyPrevious) {150 // parseInt takes a string and an optional radix151 return parseInt(value);152}15353function list(val) {54 return val.split(',');154function increaseVerbosity(dummyValue, previous) {155 return previous + 1;156}15757function collect(val, memo) {58 memo.push(val);59 return memo;158function collect(value, previous) {159 return previous.concat([value]);160}16162function increaseVerbosity(v, total) {63 return total + 1;162function commaSeparatedList(value, dummyPrevious) {163 return value.split(',');164}165166program67 .version('0.0.1')68 .usage('[options] <file ...>')69 .option('-i, --integer <n>', 'An integer argument', parseInt)70 .option('-f, --float <n>', 'A float argument', parseFloat)71 .option('-r, --range <a>..<b>', 'A range', range)72 .option('-l, --list <items>', 'A list', list)73 .option('-o, --optional [value]', 'An optional value')74 .option('-c, --collect [value]', 'A repeatable value', collect, [])75 .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)76 .parse(process.argv);167 .option('-f, --float <number>', 'float argument', parseFloat)168 .option('-i, --integer <number>', 'integer argument', myParseInt)169 .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)170 .option('-c, --collect <value>', 'repeatable value', collect, [])171 .option('-l, --list <items>', 'comma separated list', commaSeparatedList)172;17378console.log(' int: %j', program.integer);79console.log(' float: %j', program.float);80console.log(' optional: %j', program.optional);81program.range = program.range || [];82console.log(' range: %j..%j', program.range[0], program.range[1]);83console.log(' list: %j', program.list);84console.log(' collect: %j', program.collect);85console.log(' verbosity: %j', program.verbose);86console.log(' args: %j', program.args);174program.parse(process.argv);175176if (program.float !== undefined) console.log(`float: ${program.float}`);177if (program.integer !== undefined) console.log(`integer: ${program.integer}`);178if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`);179if (program.collect.length > 0) console.log(program.collect);180if (program.list !== undefined) console.log(program.list);181```182183```184$ custom -f 1e2185float: 100186$ custom --integer 2187integer: 2188$ custom -v -v -v189verbose: 3190$ custom -c a -c b -c c191[ 'a', 'b', 'c' ]192$ custom --list x,y,z193[ 'x', 'y', 'z' ]194```195196### 版本选项197198`version`方法会处理显示版本命令,默认选项标识为`-V`和`--version`,当存在时会打印版本号并退出。199200```js201 program.version('0.0.1');202```203204```205 $ ./examples/pizza -V206 0.0.1207```208209你可以自定义标识,通过给`version`方法再传递一个参数,语法给`option`方法一致。版本标识名字可以是任意的,但是必须要有长名字。210211```212program.version('0.0.1', '-v, --version');213```214215## 指定命令选项216217可以给命令绑定选项。218219```js220#!/usr/bin/env node221222var program = require('commander');223224program225 .command('rm <dir>')226 .option('-r, --recursive', 'Remove recursively')227 .action(function (dir, cmd) {228 console.log('remove ' + dir + (cmd.recursive ? ' recursively' : ''))229 })230231program.parse(process.argv)232```233234使用该命令时,将验证命令的选项。任何未知选项都将报告为错误。但是,如果基于操作的命令没有定义action,则不验证选项。235236## 正则表达式237238```js239program92 .version('0.0.1')240 .version('0.1.0')241 .option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')242 .option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)243 .parse(process.argv);244245console.log(' size: %j', program.size);246console.log(' drink: %j', program.drink);247```248249注:上面代码如果size选项传入的值和正则不匹配,则值为medium(默认值)。drink选项和正则不匹配,值为true。250251## 可变参数252253 一个命令的最后一个参数可以是可变参数, 并且只有最后一个参数可变。为了使参数可变,你需要在参数名后面追加 `...`。 下面是个示例:254
228 unmodified lines