4 [![Build Status](https://api.travis-ci.org/tj/commander.js.svg)](http://travis-ci.org/tj/commander.js)
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)
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)
9 The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/tj/commander).
10 [API documentation](http://tj.github.com/commander.js/)
15 $ npm install commander
19 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.
25 * Module dependencies.
28 var program = require('commander');
32 .option('-p, --peppers', 'Add peppers')
33 .option('-P, --pineapple', 'Add pineapple')
34 .option('-b, --bbq-sauce', 'Add bbq sauce')
35 .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
38 console.log('you ordered a pizza with:');
39 if (program.peppers) console.log(' - peppers');
40 if (program.pineapple) console.log(' - pineapple');
41 if (program.bbqSauce) console.log(' - bbq');
42 console.log(' - %s cheese', program.cheese);
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.
52 return val.split('..').map(Number);
56 return val.split(',');
59 function collect(val, memo) {
64 function increaseVerbosity(v, total) {
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)
80 console.log(' int: %j', program.integer);
81 console.log(' float: %j', program.float);
82 console.log(' optional: %j', program.optional);
83 program.range = program.range || [];
84 console.log(' range: %j..%j', program.range[0], program.range[1]);
85 console.log(' list: %j', program.list);
86 console.log(' collect: %j', program.collect);
87 console.log(' verbosity: %j', program.verbose);
88 console.log(' args: %j', program.args);
95 .option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')
96 .option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)
99 console.log(' size: %j', program.size);
100 console.log(' drink: %j', program.drink);
103 ## Variadic arguments
105 The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to
106 append `...` to the argument name. Here is an example:
112 * Module dependencies.
115 var program = require('commander');
119 .command('rmdir <dir> [otherDirs...]')
120 .action(function (dir, otherDirs) {
121 console.log('rmdir %s', dir);
123 otherDirs.forEach(function (oDir) {
124 console.log('rmdir %s', oDir);
129 program.parse(process.argv);
132 An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed
133 to your action as demonstrated above.
135 ## Specify the argument syntax
140 var program = require('../');
144 .arguments('<cmd> [env]')
145 .action(function (cmd, env) {
150 program.parse(process.argv);
152 if (typeof cmdValue === 'undefined') {
153 console.error('no command given!');
156 console.log('command:', cmdValue);
157 console.log('environment:', envValue || "no environment given");
160 ## Git-style sub-commands
163 // file: ./examples/pm
164 var program = require('..');
168 .command('install [name]', 'install one or more packages')
169 .command('search [query]', 'search with optional query')
170 .command('list', 'list packages installed', {isDefault: true})
171 .parse(process.argv);
174 When `.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.
175 The 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`.
177 Options 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.
179 If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
183 You 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.
189 The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
192 $ ./examples/pizza --help
194 Usage: pizza [options]
196 An application for pizzas ordering
200 -h, --help output usage information
201 -V, --version output the version number
202 -p, --peppers Add peppers
203 -P, --pineapple Add pineapple
204 -b, --bbq Add bbq sauce
205 -c, --cheese <type> Add the specified type of cheese [marble]
206 -C, --no-cheese You do not want any cheese
212 You can display arbitrary `-h, --help` information
213 by listening for "--help". Commander will automatically
214 exit once you are done so that the remainder of your program
215 does not execute causing undesired behaviours, for example
216 in the following executable "stuff" will not output when
223 * Module dependencies.
226 var program = require('commander');
230 .option('-f, --foo', 'enable some foo')
231 .option('-b, --bar', 'enable some bar')
232 .option('-B, --baz', 'enable some baz');
234 // must be before .parse() since
235 // node's emit() is immediate
237 program.on('--help', function(){
238 console.log(' Examples:');
240 console.log(' $ custom-help --help');
241 console.log(' $ custom-help -h');
245 program.parse(process.argv);
247 console.log('stuff');
250 Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:
254 Usage: custom-help [options]
258 -h, --help output usage information
259 -V, --version output the version number
260 -f, --foo enable some foo
261 -b, --bar enable some bar
262 -B, --baz enable some baz
273 Output help information without exiting.
274 Optional callback cb allows post-processing of help text before it is displayed.
276 If you want to display help by default (e.g. if no command was provided), you can use something like:
279 var program = require('commander');
280 var colors = require('colors');
284 .command('getstream [url]', 'get stream URL')
285 .parse(process.argv);
287 if (!process.argv.slice(2).length) {
288 program.outputHelp(make_red);
291 function make_red(txt) {
292 return colors.red(txt); //display the help text in red on the console
298 Output help information and exit immediately.
299 Optional callback cb allows post-processing of help text before it is displayed.
304 var program = require('commander');
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')
313 .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";
319 console.log('setup for %s env(s) with %s mode', env, mode);
323 .command('exec <cmd>')
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:');
332 console.log(' $ deploy exec sequential');
333 console.log(' $ deploy exec async');
339 .action(function(env){
340 console.log('deploying "%s"', env);
343 program.parse(process.argv);
346 More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.