15bb42aeac16f0d6d33a967a0ccc773dff5933f2a794ac5f32d08b6f9e0d1ae411d7a10c593bc61f0886f9831e964c2537100e47d0dfac5eb53e5501bda7f1 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. # Commander.js
  2. [![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js)
  3. [![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
  4. [![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
  5. [![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)
  6. [![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)
  7. The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander).
  8. [API documentation](http://tj.github.com/commander.js/)
  9. ## Installation
  10. $ npm install commander
  11. ## Option parsing
  12. 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.
  13. ```js
  14. #!/usr/bin/env node
  15. /**
  16. * Module dependencies.
  17. */
  18. var program = require('commander');
  19. program
  20. .version('0.1.0')
  21. .option('-p, --peppers', 'Add peppers')
  22. .option('-P, --pineapple', 'Add pineapple')
  23. .option('-b, --bbq-sauce', 'Add bbq sauce')
  24. .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
  25. .parse(process.argv);
  26. console.log('you ordered a pizza with:');
  27. if (program.peppers) console.log(' - peppers');
  28. if (program.pineapple) console.log(' - pineapple');
  29. if (program.bbqSauce) console.log(' - bbq');
  30. console.log(' - %s cheese', program.cheese);
  31. ```
  32. 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.
  33. 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.
  34. ```js
  35. #!/usr/bin/env node
  36. /**
  37. * Module dependencies.
  38. */
  39. var program = require('commander');
  40. program
  41. .option('--no-sauce', 'Remove sauce')
  42. .parse(process.argv);
  43. console.log('you ordered a pizza');
  44. if (program.sauce) console.log(' with sauce');
  45. else console.log(' without sauce');
  46. ```
  47. To get string arguments from options you will need to use angle brackets <> for required inputs or square brackets [] for optional inputs.
  48. e.g. ```.option('-m --myarg [myVar]', 'my super cool description')```
  49. Then to access the input if it was passed in.
  50. e.g. ```var myInput = program.myarg```
  51. **NOTE**: If you pass a argument without using brackets the example above will return true and not the value passed in.
  52. ## Version option
  53. Calling the `version` implicitly adds the `-V` and `--version` options to the command.
  54. When either of these options is present, the command prints the version number and exits.
  55. $ ./examples/pizza -V
  56. 0.0.1
  57. 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.
  58. ```js
  59. program
  60. .version('0.0.1', '-v, --version')
  61. ```
  62. The version flags can be named anything, but the long option is required.
  63. ## Command-specific options
  64. You can attach options to a command.
  65. ```js
  66. #!/usr/bin/env node
  67. var program = require('commander');
  68. program
  69. .command('rm <dir>')
  70. .option('-r, --recursive', 'Remove recursively')
  71. .action(function (dir, cmd) {
  72. console.log('remove ' + dir + (cmd.recursive ? ' recursively' : ''))
  73. })
  74. program.parse(process.argv)
  75. ```
  76. 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.
  77. ## Coercion
  78. ```js
  79. function range(val) {
  80. return val.split('..').map(Number);
  81. }
  82. function list(val) {
  83. return val.split(',');
  84. }
  85. function collect(val, memo) {
  86. memo.push(val);
  87. return memo;
  88. }
  89. function increaseVerbosity(v, total) {
  90. return total + 1;
  91. }
  92. program
  93. .version('0.1.0')
  94. .usage('[options] <file ...>')
  95. .option('-i, --integer <n>', 'An integer argument', parseInt)
  96. .option('-f, --float <n>', 'A float argument', parseFloat)
  97. .option('-r, --range <a>..<b>', 'A range', range)
  98. .option('-l, --list <items>', 'A list', list)
  99. .option('-o, --optional [value]', 'An optional value')
  100. .option('-c, --collect [value]', 'A repeatable value', collect, [])
  101. .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
  102. .parse(process.argv);
  103. console.log(' int: %j', program.integer);
  104. console.log(' float: %j', program.float);
  105. console.log(' optional: %j', program.optional);
  106. program.range = program.range || [];
  107. console.log(' range: %j..%j', program.range[0], program.range[1]);
  108. console.log(' list: %j', program.list);
  109. console.log(' collect: %j', program.collect);
  110. console.log(' verbosity: %j', program.verbose);
  111. console.log(' args: %j', program.args);
  112. ```
  113. ## Regular Expression
  114. ```js
  115. program
  116. .version('0.1.0')
  117. .option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')
  118. .option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)
  119. .parse(process.argv);
  120. console.log(' size: %j', program.size);
  121. console.log(' drink: %j', program.drink);
  122. ```
  123. ## Variadic arguments
  124. The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to
  125. append `...` to the argument name. Here is an example:
  126. ```js
  127. #!/usr/bin/env node
  128. /**
  129. * Module dependencies.
  130. */
  131. var program = require('commander');
  132. program
  133. .version('0.1.0')
  134. .command('rmdir <dir> [otherDirs...]')
  135. .action(function (dir, otherDirs) {
  136. console.log('rmdir %s', dir);
  137. if (otherDirs) {
  138. otherDirs.forEach(function (oDir) {
  139. console.log('rmdir %s', oDir);
  140. });
  141. }
  142. });
  143. program.parse(process.argv);
  144. ```
  145. An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed
  146. to your action as demonstrated above.
  147. ## Specify the argument syntax
  148. ```js
  149. #!/usr/bin/env node
  150. var program = require('commander');
  151. program
  152. .version('0.1.0')
  153. .arguments('<cmd> [env]')
  154. .action(function (cmd, env) {
  155. cmdValue = cmd;
  156. envValue = env;
  157. });
  158. program.parse(process.argv);
  159. if (typeof cmdValue === 'undefined') {
  160. console.error('no command given!');
  161. process.exit(1);
  162. }
  163. console.log('command:', cmdValue);
  164. console.log('environment:', envValue || "no environment given");
  165. ```
  166. Angled brackets (e.g. `<cmd>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input.
  167. ## Git-style sub-commands
  168. ```js
  169. // file: ./examples/pm
  170. var program = require('commander');
  171. program
  172. .version('0.1.0')
  173. .command('install [name]', 'install one or more packages')
  174. .command('search [query]', 'search with optional query')
  175. .command('list', 'list packages installed', {isDefault: true})
  176. .parse(process.argv);
  177. ```
  178. 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.
  179. 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`.
  180. Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the subcommand from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.
  181. If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
  182. ### `--harmony`
  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.
  186. ## Automated --help
  187. The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
  188. ```
  189. $ ./examples/pizza --help
  190. Usage: pizza [options]
  191. An application for pizzas ordering
  192. Options:
  193. -h, --help output usage information
  194. -V, --version output the version number
  195. -p, --peppers Add peppers
  196. -P, --pineapple Add pineapple
  197. -b, --bbq Add bbq sauce
  198. -c, --cheese <type> Add the specified type of cheese [marble]
  199. -C, --no-cheese You do not want any cheese
  200. ```
  201. ## Custom help
  202. You can display arbitrary `-h, --help` information
  203. by listening for "--help". Commander will automatically
  204. exit once you are done so that the remainder of your program
  205. does not execute causing undesired behaviors, for example
  206. in the following executable "stuff" will not output when
  207. `--help` is used.
  208. ```js
  209. #!/usr/bin/env node
  210. /**
  211. * Module dependencies.
  212. */
  213. var program = require('commander');
  214. program
  215. .version('0.1.0')
  216. .option('-f, --foo', 'enable some foo')
  217. .option('-b, --bar', 'enable some bar')
  218. .option('-B, --baz', 'enable some baz');
  219. // must be before .parse() since
  220. // node's emit() is immediate
  221. program.on('--help', function(){
  222. console.log('')
  223. console.log('Examples:');
  224. console.log(' $ custom-help --help');
  225. console.log(' $ custom-help -h');
  226. });
  227. program.parse(process.argv);
  228. console.log('stuff');
  229. ```
  230. Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:
  231. ```
  232. Usage: custom-help [options]
  233. Options:
  234. -h, --help output usage information
  235. -V, --version output the version number
  236. -f, --foo enable some foo
  237. -b, --bar enable some bar
  238. -B, --baz enable some baz
  239. Examples:
  240. $ custom-help --help
  241. $ custom-help -h
  242. ```
  243. ## .outputHelp(cb)
  244. Output help information without exiting.
  245. Optional callback cb allows post-processing of help text before it is displayed.
  246. If you want to display help by default (e.g. if no command was provided), you can use something like:
  247. ```js
  248. var program = require('commander');
  249. var colors = require('colors');
  250. program
  251. .version('0.1.0')
  252. .command('getstream [url]', 'get stream URL')
  253. .parse(process.argv);
  254. if (!process.argv.slice(2).length) {
  255. program.outputHelp(make_red);
  256. }
  257. function make_red(txt) {
  258. return colors.red(txt); //display the help text in red on the console
  259. }
  260. ```
  261. ## .help(cb)
  262. Output help information and exit immediately.
  263. Optional callback cb allows post-processing of help text before it is displayed.
  264. ## Custom event listeners
  265. You can execute custom actions by listening to command and option events.
  266. ```js
  267. program.on('option:verbose', function () {
  268. process.env.VERBOSE = this.verbose;
  269. });
  270. // error on unknown commands
  271. program.on('command:*', function () {
  272. console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' '));
  273. process.exit(1);
  274. });
  275. ```
  276. ## Examples
  277. ```js
  278. var program = require('commander');
  279. program
  280. .version('0.1.0')
  281. .option('-C, --chdir <path>', 'change the working directory')
  282. .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
  283. .option('-T, --no-tests', 'ignore test hook');
  284. program
  285. .command('setup [env]')
  286. .description('run setup commands for all envs')
  287. .option("-s, --setup_mode [mode]", "Which setup mode to use")
  288. .action(function(env, options){
  289. var mode = options.setup_mode || "normal";
  290. env = env || 'all';
  291. console.log('setup for %s env(s) with %s mode', env, mode);
  292. });
  293. program
  294. .command('exec <cmd>')
  295. .alias('ex')
  296. .description('execute the given remote cmd')
  297. .option("-e, --exec_mode <mode>", "Which exec mode to use")
  298. .action(function(cmd, options){
  299. console.log('exec "%s" using %s mode', cmd, options.exec_mode);
  300. }).on('--help', function() {
  301. console.log('');
  302. console.log('Examples:');
  303. console.log('');
  304. console.log(' $ deploy exec sequential');
  305. console.log(' $ deploy exec async');
  306. });
  307. program
  308. .command('*')
  309. .action(function(env){
  310. console.log('deploying "%s"', env);
  311. });
  312. program.parse(process.argv);
  313. ```
  314. More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
  315. ## License
  316. [MIT](https://github.com/tj/commander.js/blob/master/LICENSE)