Skip to content
Myr

Readme.md

This file

Path

Readme.md

351 lines · 9.9 KiB · Markdown

Last changed by

add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9

History of this file

Take it

The walk stopped after 200 commits: lines older than 663b313 point at it.

docsTj Holowaychukbefore adoption663b313

lines 1–2why, one step back
1# Commander.js
2

Merge pull request #356 from gitter-badger/gitter-badgeZhiye Libefore adoption54583a3

line 3why, one step back
3

Merge pull request #358 from zhiyelee/gitterZhiye Libefore adoption5ae016f

line 4why, one step back
4[![Build Status](https://api.travis-ci.org/tj/commander.js.svg)](http://travis-ci.org/tj/commander.js)

Merge pull request #279 from zhiyelee/readmeZhiye Libefore adoption558169f

lines 5–6why, one step back
5[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
6[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://www.npmjs.org/package/commander)

Merge pull request #358 from zhiyelee/gitterZhiye Libefore adoption5ae016f

line 7why, one step back
7[![Join the chat at https://gitter.im/tj/commander.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

docsTj Holowaychukbefore adoption663b313

line 8why, one step back
8

Merge pull request #300 from zhiyelee/ghreadZhiye Libefore adoption1444cf3

line 9why, one step back
9 The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/tj/commander).

reorganize readmezhiyeleebefore adoption79f04b3

line 10why, one step back
10 [API documentation](http://tj.github.com/commander.js/)

Merge pull request #279 from zhiyelee/readmeZhiye Libefore adoption558169f

line 11why, one step back
11

travis badgeTj Holowaychukbefore adoptione33a6cf

line 12why, one step back
12

docsTj Holowaychukbefore adoption663b313

lines 13–27why, one step back
13## Installation
1415 $ npm install commander1617## Option parsing1819 Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.2021```js22#!/usr/bin/env node2324/**25 * Module dependencies.26 */27

typoTj Holowaychukbefore adoption20e5d98

line 28why, one step back
28var program = require('commander');

docsTj Holowaychukbefore adoption663b313

lines 29–33why, one step back
29
30program31 .version('0.0.1')32 .option('-p, --peppers', 'Add peppers')33 .option('-P, --pineapple', 'Add pineapple')

Merge pull request #371 from malthejorgensen/readme-camelcase-exampleZhiye Libefore adoptione326d94

line 34why, one step back
34 .option('-b, --bbq-sauce', 'Add bbq sauce')

docsTj Holowaychukbefore adoptiond721114

line 35why, one step back
35 .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')

docsTj Holowaychukbefore adoption663b313

lines 36–39why, one step back
36 .parse(process.argv);
3738console.log('you ordered a pizza with:');39if (program.peppers) console.log(' - peppers');

Merge pull request #158 from ChrisWren/masterTJ Holowaychukbefore adoption62cd70c

line 40why, one step back
40if (program.pineapple) console.log(' - pineapple');

Merge pull request #371 from malthejorgensen/readme-camelcase-exampleZhiye Libefore adoptione326d94

line 41why, one step back
41if (program.bbqSauce) console.log(' - bbq');

docsTj Holowaychukbefore adoptiona72b2da

line 42why, one step back
42console.log(' - %s cheese', program.cheese);

docsTj Holowaychukbefore adoption663b313

lines 43–44why, one step back
43```
44

camel-case docsTj Holowaychukbefore adoption6a686c1

line 45why, one step back
45 Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.

docsTj Holowaychukbefore adoption663b313

line 46why, one step back
46

reorganize readmezhiyeleebefore adoption79f04b3

lines 47–90why, one step back
47
48## Coercion4950```js51function range(val) {52 return val.split('..').map(Number);53}5455function list(val) {56 return val.split(',');57}5859function collect(val, memo) {60 memo.push(val);61 return memo;62}6364function increaseVerbosity(v, total) {65 return total + 1;66}6768program69 .version('0.0.1')70 .usage('[options] <file ...>')71 .option('-i, --integer <n>', 'An integer argument', parseInt)72 .option('-f, --float <n>', 'A float argument', parseFloat)73 .option('-r, --range <a>..<b>', 'A range', range)74 .option('-l, --list <items>', 'A list', list)75 .option('-o, --optional [value]', 'An optional value')76 .option('-c, --collect [value]', 'A repeatable value', collect, [])77 .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)78 .parse(process.argv);7980console.log(' int: %j', program.integer);81console.log(' float: %j', program.float);82console.log(' optional: %j', program.optional);83program.range = program.range || [];84console.log(' range: %j..%j', program.range[0], program.range[1]);85console.log(' list: %j', program.list);86console.log(' collect: %j', program.collect);87console.log(' verbosity: %j', program.verbose);88console.log(' args: %j', program.args);89```90

Merge pull request #337 from palanik/masterRandall Koutnikbefore adoption46f9c52

lines 91–102why, one step back
91## Regular Expression
92```js93program94 .version('0.0.1')95 .option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')96 .option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)97 .parse(process.argv);98 99console.log(' size: %j', program.size);100console.log(' drink: %j', program.drink);101```102

Merge pull request #277 from whitlockjc/fix-issue-53Zhiye Libefore adoptionaf05389

lines 103–126why, one step back
103## Variadic arguments
104105 The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to106 append `...` to the argument name. Here is an example:107108```js109#!/usr/bin/env node110111/**112 * Module dependencies.113 */114115var program = require('commander');116117program118 .version('0.0.1')119 .command('rmdir <dir> [otherDirs...]')120 .action(function (dir, otherDirs) {121 console.log('rmdir %s', dir);122 if (otherDirs) {123 otherDirs.forEach(function (oDir) {124 console.log('rmdir %s', oDir);125 });126 }

Merge pull request #280 from zhiyelee/fixdemoZhiye Libefore adoption2878611

lines 127–129why, one step back
127 });
128129program.parse(process.argv);

Merge pull request #277 from whitlockjc/fix-issue-53Zhiye Libefore adoptionaf05389

lines 130–134why, one step back
130```
131132 An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed133 to your action as demonstrated above.134

Merge pull request #392 from rrthomas/document-argumentsRandall Koutnikbefore adoptionc6ddd55

lines 135–159why, one step back
135## Specify the argument syntax
136137```js138#!/usr/bin/env node139140var program = require('../');141142program143 .version('0.0.1')144 .arguments('<cmd> [env]')145 .action(function (cmd, env) {146 cmdValue = cmd;147 envValue = env;148 });149150program.parse(process.argv);151152if (typeof cmdValue === 'undefined') {153 console.error('no command given!');154 process.exit(1);155}156console.log('command:', cmdValue);157console.log('environment:', envValue || "no environment given");158```159

Merge pull request #295 from zhiyelee/git-style-readmeZhiye Libefore adoptionfc543c8

lines 160–169why, one step back
160## Git-style sub-commands
161162```js163// file: ./examples/pm164var program = require('..');165166program167 .version('0.0.1')168 .command('install [name]', 'install one or more packages')169 .command('search [query]', 'search with optional query')

Merge pull request #415 from Qix-/default-subcommandRandall Koutnikbefore adoption0af40a5

line 170why, one step back
170 .command('list', 'list packages installed', {isDefault: true})

Merge pull request #295 from zhiyelee/git-style-readmeZhiye Libefore adoptionfc543c8

lines 171–174why, one step back
171 .parse(process.argv);
172```173174When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools.

Merge pull request #366 from zhiyelee/typoZhiye Libefore adoption481e943

line 175why, one step back
175The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`.

Merge pull request #415 from Qix-/default-subcommandRandall Koutnikbefore adoption0af40a5

lines 176–177why, one step back
176
177Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the option from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.

Merge pull request #295 from zhiyelee/git-style-readmeZhiye Libefore adoptionfc543c8

line 178why, one step back
178

Merge pull request #381 from radiovisual/masterZhiye Libefore adoptionada4787

line 179why, one step back
179If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.

Merge pull request #365 from zhiyelee/subcommandZhiye Libefore adoption0109a44

line 180why, one step back
180

Merge pull request #391 from zhiyelee/newversionZhiye Libefore adoption4dae21d

lines 181–186why, one step back
181### `--harmony`
182183You can enable `--harmony` option in two ways:184* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version don’t support this pattern.185* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process.186

docsTj Holowaychukbefore adoption663b313

lines 187–195why, one step back
187## Automated --help
188189 The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:190191``` 192 $ ./examples/pizza --help193194 Usage: pizza [options]195

Merge pull request #316 from zhiyelee/updatereadmeZhiye Libefore adoption0b95ea2

lines 196–197why, one step back
196 An application for pizzas ordering
197

docsTj Holowaychukbefore adoption663b313

lines 198–199why, one step back
198 Options:
199

Merge pull request #316 from zhiyelee/updatereadmeZhiye Libefore adoption0b95ea2

line 200why, one step back
200 -h, --help output usage information

Merge branch 'master' of github.com:visionmedia/commander.jsTJ Holowaychukbefore adoptionef02666

line 201why, one step back
201 -V, --version output the version number

docsTj Holowaychukbefore adoption663b313

line 202why, one step back
202 -p, --peppers Add peppers

Merge pull request #158 from ChrisWren/masterTJ Holowaychukbefore adoption62cd70c

line 203why, one step back
203 -P, --pineapple Add pineapple

docsTj Holowaychukbefore adoption663b313

line 204why, one step back
204 -b, --bbq Add bbq sauce

Merge pull request #397 from tj/revert-208-feature/descriptions-multiline-supportZhiye Libefore adoption64a5a5d

line 205why, one step back
205 -c, --cheese <type> Add the specified type of cheese [marble]

Merge pull request #316 from zhiyelee/updatereadmeZhiye Libefore adoption0b95ea2

line 206why, one step back
206 -C, --no-cheese You do not want any cheese

docsTj Holowaychukbefore adoption663b313

lines 207–209why, one step back
207
208```209

Added support for custom --help outputTj Holowaychukbefore adoptionda13783

lines 210–225why, one step back
210## Custom help
211212 You can display arbitrary `-h, --help` information213 by listening for "--help". Commander will automatically214 exit once you are done so that the remainder of your program215 does not execute causing undesired behaviours, for example216 in the following executable "stuff" will not output when217 `--help` is used.218219```js220#!/usr/bin/env node221222/**223 * Module dependencies.224 */225

Updated Readme.md to make custom help example portableThomas Geraghtybefore adoption79ea120

line 226why, one step back
226var program = require('commander');

Added support for custom --help outputTj Holowaychukbefore adoptionda13783

lines 227–249why, one step back
227
228program229 .version('0.0.1')230 .option('-f, --foo', 'enable some foo')231 .option('-b, --bar', 'enable some bar')232 .option('-B, --baz', 'enable some baz');233234// must be before .parse() since235// node's emit() is immediate236237program.on('--help', function(){238 console.log(' Examples:');239 console.log('');240 console.log(' $ custom-help --help');241 console.log(' $ custom-help -h');242 console.log('');243});244245program.parse(process.argv);246247console.log('stuff');248```249

Updated Readme.md to make custom help example portableThomas Geraghtybefore adoption79ea120

line 250why, one step back
250Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:

Added support for custom --help outputTj Holowaychukbefore adoptionda13783

lines 251–258why, one step back
251
252```253254Usage: custom-help [options]255256Options:257258 -h, --help output usage information

Merge branch 'master' of github.com:visionmedia/commander.jsTJ Holowaychukbefore adoptionef02666

line 259why, one step back
259 -V, --version output the version number

Added support for custom --help outputTj Holowaychukbefore adoptionda13783

lines 260–270why, one step back
260 -f, --foo enable some foo
261 -b, --bar enable some bar262 -B, --baz enable some baz263264Examples:265266 $ custom-help --help267 $ custom-help -h268269```270

add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9

line 271why, one step back
271## .outputHelp(cb)

docsTJ Holowaychukbefore adoptionf5078e2

line 272why, one step back
272

add `outputhelp` usage tipzhiyeleebefore adoption0d842dc

line 273why, one step back
273Output help information without exiting.

add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9

line 274why, one step back
274Optional callback cb allows post-processing of help text before it is displayed.

add `outputhelp` usage tipzhiyeleebefore adoption0d842dc

lines 275–279why, one step back
275
276If you want to display help by default (e.g. if no command was provided), you can use something like:277278```js279var program = require('commander');

add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9

line 280why, one step back
280var colors = require('colors');

add `outputhelp` usage tipzhiyeleebefore adoption0d842dc

lines 281–287why, one step back
281
282program283 .version('0.0.1')284 .command('getstream [url]', 'get stream URL')285 .parse(process.argv);286287 if (!process.argv.slice(2).length) {

add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9

line 288why, one step back
288 program.outputHelp(make_red);

add `outputhelp` usage tipzhiyeleebefore adoption0d842dc

line 289why, one step back
289 }

add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9

lines 290–293why, one step back
290
291function make_red(txt) {292 return colors.red(txt); //display the help text in red on the console293}

add `outputhelp` usage tipzhiyeleebefore adoption0d842dc

line 294why, one step back
294```

docsTJ Holowaychukbefore adoptionf5078e2

line 295why, one step back
295

add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9

line 296why, one step back
296## .help(cb)

docsTJ Holowaychukbefore adoptionf5078e2

lines 297–298why, one step back
297
298 Output help information and exit immediately.

add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9

line 299why, one step back
299 Optional callback cb allows post-processing of help text before it is displayed.

docsTJ Holowaychukbefore adoptionf5078e2

line 300why, one step back
300

reorganize readmezhiyeleebefore adoption79f04b3

line 301why, one step back
301## Examples

docsTj Holowaychukbefore adoption663b313

line 302why, one step back
302

reorganize readmezhiyeleebefore adoption79f04b3

lines 303–345why, one step back
303```js
304var program = require('commander');305306program307 .version('0.0.1')308 .option('-C, --chdir <path>', 'change the working directory')309 .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')310 .option('-T, --no-tests', 'ignore test hook')311312program313 .command('setup [env]')314 .description('run setup commands for all envs')315 .option("-s, --setup_mode [mode]", "Which setup mode to use")316 .action(function(env, options){317 var mode = options.setup_mode || "normal";318 env = env || 'all';319 console.log('setup for %s env(s) with %s mode', env, mode);320 });321322program323 .command('exec <cmd>')324 .alias('ex')325 .description('execute the given remote cmd')326 .option("-e, --exec_mode <mode>", "Which exec mode to use")327 .action(function(cmd, options){328 console.log('exec "%s" using %s mode', cmd, options.exec_mode);329 }).on('--help', function() {330 console.log(' Examples:');331 console.log();332 console.log(' $ deploy exec sequential');333 console.log(' $ deploy exec async');334 console.log();335 });336337program338 .command('*')339 .action(function(env){340 console.log('deploying "%s"', env);341 });342343program.parse(process.argv);344```345

Merge pull request #366 from zhiyelee/typoZhiye Libefore adoption481e943

line 346why, one step back
346More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.

docsTj Holowaychukbefore adoption663b313

line 347why, one step back
347

Merge pull request #277 from whitlockjc/fix-issue-53Zhiye Libefore adoptionaf05389

line 348why, one step back
348## License

docsTj Holowaychukbefore adoption663b313

line 349why, one step back
349

Merge pull request #365 from zhiyelee/subcommandZhiye Libefore adoption0109a44

line 350why, one step back
350MIT

docsTj Holowaychukbefore adoption663b313

line 351why, one step back
351