You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Readme.md 9.3KB

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