585e073cc86d1d4523fb0ea1badea1e463beea447e519ab698b96cc0bac84537e1a59433a76e30822bbbdd6153b64409721981773255337d63efe9e2e1f823 10 KB

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