4 [![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](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://npmcharts.com/compare/commander?minimal=true)
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/commander-rb/commander).
10 [API documentation](http://tj.github.com/commander.js/)
15 $ npm install commander --save
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.
47 Note that multi-word options starting with `--no` prefix negate the boolean value of the following word. For example, `--no-sauce` sets the value of `program.sauce` to false.
53 * Module dependencies.
56 var program = require('commander');
59 .option('--no-sauce', 'Remove sauce')
62 console.log('you ordered a pizza');
63 if (program.sauce) console.log(' with sauce');
64 else console.log(' without sauce');
69 Calling the `version` implicitly adds the `-V` and `--version` options to the command.
70 When either of these options is present, the command prints the version number and exits.
75 If you want your program to respond to the `-v` option instead of the `-V` option, simply pass custom flags to the `version` method using the same syntax as the `option` method.
79 .version('0.0.1', '-v, --version')
82 The version flags can be named anything, but the long option is required.
84 ## Command-specific options
86 You can attach options to a command.
91 var program = require('commander');
95 .option('-r, --recursive', 'Remove recursively')
96 .action(function (dir, cmd) {
97 console.log('remove ' + dir + (cmd.recursive ? ' recursively' : ''))
100 program.parse(process.argv)
103 A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.
108 function range(val) {
109 return val.split('..').map(Number);
113 return val.split(',');
116 function collect(val, memo) {
121 function increaseVerbosity(v, total) {
127 .usage('[options] <file ...>')
128 .option('-i, --integer <n>', 'An integer argument', parseInt)
129 .option('-f, --float <n>', 'A float argument', parseFloat)
130 .option('-r, --range <a>..<b>', 'A range', range)
131 .option('-l, --list <items>', 'A list', list)
132 .option('-o, --optional [value]', 'An optional value')
133 .option('-c, --collect [value]', 'A repeatable value', collect, [])
134 .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
135 .parse(process.argv);
137 console.log(' int: %j', program.integer);
138 console.log(' float: %j', program.float);
139 console.log(' optional: %j', program.optional);
140 program.range = program.range || [];
141 console.log(' range: %j..%j', program.range[0], program.range[1]);
142 console.log(' list: %j', program.list);
143 console.log(' collect: %j', program.collect);
144 console.log(' verbosity: %j', program.verbose);
145 console.log(' args: %j', program.args);
148 ## Regular Expression
152 .option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')
153 .option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)
154 .parse(process.argv);
156 console.log(' size: %j', program.size);
157 console.log(' drink: %j', program.drink);
160 ## Variadic arguments
162 The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to
163 append `...` to the argument name. Here is an example:
169 * Module dependencies.
172 var program = require('commander');
176 .command('rmdir <dir> [otherDirs...]')
177 .action(function (dir, otherDirs) {
178 console.log('rmdir %s', dir);
180 otherDirs.forEach(function (oDir) {
181 console.log('rmdir %s', oDir);
186 program.parse(process.argv);
189 An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed
190 to your action as demonstrated above.
192 ## Specify the argument syntax
197 var program = require('commander');
201 .arguments('<cmd> [env]')
202 .action(function (cmd, env) {
207 program.parse(process.argv);
209 if (typeof cmdValue === 'undefined') {
210 console.error('no command given!');
213 console.log('command:', cmdValue);
214 console.log('environment:', envValue || "no environment given");
216 Angled brackets (e.g. `<cmd>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input.
218 ## Git-style sub-commands
221 // file: ./examples/pm
222 var program = require('commander');
226 .command('install [name]', 'install one or more packages')
227 .command('search [query]', 'search with optional query')
228 .command('list', 'list packages installed', {isDefault: true})
229 .parse(process.argv);
232 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.
233 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`.
235 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.
237 If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
241 You can enable `--harmony` option in two ways:
242 * Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version don’t support this pattern.
243 * 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.
247 The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
250 $ ./examples/pizza --help
252 Usage: pizza [options]
254 An application for pizzas ordering
258 -h, --help output usage information
259 -V, --version output the version number
260 -p, --peppers Add peppers
261 -P, --pineapple Add pineapple
262 -b, --bbq Add bbq sauce
263 -c, --cheese <type> Add the specified type of cheese [marble]
264 -C, --no-cheese You do not want any cheese
270 You can display arbitrary `-h, --help` information
271 by listening for "--help". Commander will automatically
272 exit once you are done so that the remainder of your program
273 does not execute causing undesired behaviours, for example
274 in the following executable "stuff" will not output when
281 * Module dependencies.
284 var program = require('commander');
288 .option('-f, --foo', 'enable some foo')
289 .option('-b, --bar', 'enable some bar')
290 .option('-B, --baz', 'enable some baz');
292 // must be before .parse() since
293 // node's emit() is immediate
295 program.on('--help', function(){
296 console.log(' Examples:');
298 console.log(' $ custom-help --help');
299 console.log(' $ custom-help -h');
303 program.parse(process.argv);
305 console.log('stuff');
308 Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:
312 Usage: custom-help [options]
316 -h, --help output usage information
317 -V, --version output the version number
318 -f, --foo enable some foo
319 -b, --bar enable some bar
320 -B, --baz enable some baz
331 Output help information without exiting.
332 Optional callback cb allows post-processing of help text before it is displayed.
334 If you want to display help by default (e.g. if no command was provided), you can use something like:
337 var program = require('commander');
338 var colors = require('colors');
342 .command('getstream [url]', 'get stream URL')
343 .parse(process.argv);
345 if (!process.argv.slice(2).length) {
346 program.outputHelp(make_red);
349 function make_red(txt) {
350 return colors.red(txt); //display the help text in red on the console
356 Output help information and exit immediately.
357 Optional callback cb allows post-processing of help text before it is displayed.
362 var program = require('commander');
366 .option('-C, --chdir <path>', 'change the working directory')
367 .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
368 .option('-T, --no-tests', 'ignore test hook');
371 .command('setup [env]')
372 .description('run setup commands for all envs')
373 .option("-s, --setup_mode [mode]", "Which setup mode to use")
374 .action(function(env, options){
375 var mode = options.setup_mode || "normal";
377 console.log('setup for %s env(s) with %s mode', env, mode);
381 .command('exec <cmd>')
383 .description('execute the given remote cmd')
384 .option("-e, --exec_mode <mode>", "Which exec mode to use")
385 .action(function(cmd, options){
386 console.log('exec "%s" using %s mode', cmd, options.exec_mode);
387 }).on('--help', function() {
388 console.log(' Examples:');
390 console.log(' $ deploy exec sequential');
391 console.log(' $ deploy exec async');
397 .action(function(env){
398 console.log('deploying "%s"', env);
401 program.parse(process.argv);
404 More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.