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.

425 lines
12 KiB

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