Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
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 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander).
  7. Read this in other languages: English | [简体中文](./Readme_zh-CN.md)
  8. - [Commander.js](#commanderjs)
  9. - [Installation](#installation)
  10. - [Declaring _program_ variable](#declaring-program-variable)
  11. - [Options](#options)
  12. - [Common option types, boolean and value](#common-option-types-boolean-and-value)
  13. - [Default option value](#default-option-value)
  14. - [Other option types, negatable boolean and flag|value](#other-option-types-negatable-boolean-and-flagvalue)
  15. - [Custom option processing](#custom-option-processing)
  16. - [Required option](#required-option)
  17. - [Version option](#version-option)
  18. - [Commands](#commands)
  19. - [Specify the argument syntax](#specify-the-argument-syntax)
  20. - [Action handler (sub)commands](#action-handler-subcommands)
  21. - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)
  22. - [Automated help](#automated-help)
  23. - [Custom help](#custom-help)
  24. - [.usage and .name](#usage-and-name)
  25. - [.help(cb)](#helpcb)
  26. - [.outputHelp(cb)](#outputhelpcb)
  27. - [.helpInformation()](#helpinformation)
  28. - [.helpOption(flags, description)](#helpoptionflags-description)
  29. - [.addHelpCommand()](#addhelpcommand)
  30. - [Custom event listeners](#custom-event-listeners)
  31. - [Bits and pieces](#bits-and-pieces)
  32. - [.parse() and .parseAsync()](#parse-and-parseasync)
  33. - [Avoiding option name clashes](#avoiding-option-name-clashes)
  34. - [TypeScript](#typescript)
  35. - [createCommand()](#createcommand)
  36. - [Node options such as `--harmony`](#node-options-such-as---harmony)
  37. - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)
  38. - [Override exit handling](#override-exit-handling)
  39. - [Examples](#examples)
  40. - [License](#license)
  41. - [Support](#support)
  42. - [Commander for enterprise](#commander-for-enterprise)
  43. ## Installation
  44. ```bash
  45. npm install commander
  46. ```
  47. ## Declaring _program_ variable
  48. Commander exports a global object which is convenient for quick programs.
  49. This is used in the examples in this README for brevity.
  50. ```js
  51. const { program } = require('commander');
  52. program.version('0.0.1');
  53. ```
  54. For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.
  55. ```js
  56. const { Command } = require('commander');
  57. const program = new Command();
  58. program.version('0.0.1');
  59. ```
  60. ## Options
  61. Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space or vertical bar ('|').
  62. The options can be accessed as properties on the Command object. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. See also optional new behaviour to [avoid name clashes](#avoiding-option-name-clashes).
  63. Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, the last flag may take a value, and the value.
  64. For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`.
  65. You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.
  66. This is particularly useful for passing options through to another
  67. command, like: `do -- git --version`.
  68. Options on the command line are not positional, and can be specified before or after other command arguments.
  69. ### Common option types, boolean and value
  70. The two most used option types are a boolean flag, and an option which takes a value (declared using angle brackets). Both are `undefined` unless specified on command line.
  71. ```js
  72. const { program } = require('commander');
  73. program
  74. .option('-d, --debug', 'output extra debugging')
  75. .option('-s, --small', 'small pizza size')
  76. .option('-p, --pizza-type <type>', 'flavour of pizza');
  77. program.parse(process.argv);
  78. if (program.debug) console.log(program.opts());
  79. console.log('pizza details:');
  80. if (program.small) console.log('- small pizza size');
  81. if (program.pizzaType) console.log(`- ${program.pizzaType}`);
  82. ```
  83. ```bash
  84. $ pizza-options -d
  85. { debug: true, small: undefined, pizzaType: undefined }
  86. pizza details:
  87. $ pizza-options -p
  88. error: option '-p, --pizza-type <type>' argument missing
  89. $ pizza-options -ds -p vegetarian
  90. { debug: true, small: true, pizzaType: 'vegetarian' }
  91. pizza details:
  92. - small pizza size
  93. - vegetarian
  94. $ pizza-options --pizza-type=cheese
  95. pizza details:
  96. - cheese
  97. ```
  98. `program.parse(arguments)` processes the arguments, leaving any args not consumed by the program options in the `program.args` array.
  99. ### Default option value
  100. You can specify a default value for an option which takes a value.
  101. ```js
  102. const { program } = require('commander');
  103. program
  104. .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');
  105. program.parse(process.argv);
  106. console.log(`cheese: ${program.cheese}`);
  107. ```
  108. ```bash
  109. $ pizza-options
  110. cheese: blue
  111. $ pizza-options --cheese stilton
  112. cheese: stilton
  113. ```
  114. ### Other option types, negatable boolean and flag|value
  115. You can specify a boolean option long name with a leading `no-` to set the option value to false when used.
  116. Defined alone this also makes the option true by default.
  117. If you define `--foo` first, adding `--no-foo` does not change the default value from what it would
  118. otherwise be. You can specify a default boolean value for a boolean flag and it can be overridden on command line.
  119. ```js
  120. const { program } = require('commander');
  121. program
  122. .option('--no-sauce', 'Remove sauce')
  123. .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')
  124. .option('--no-cheese', 'plain with no cheese')
  125. .parse(process.argv);
  126. const sauceStr = program.sauce ? 'sauce' : 'no sauce';
  127. const cheeseStr = (program.cheese === false) ? 'no cheese' : `${program.cheese} cheese`;
  128. console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);
  129. ```
  130. ```bash
  131. $ pizza-options
  132. You ordered a pizza with sauce and mozzarella cheese
  133. $ pizza-options --sauce
  134. error: unknown option '--sauce'
  135. $ pizza-options --cheese=blue
  136. You ordered a pizza with sauce and blue cheese
  137. $ pizza-options --no-sauce --no-cheese
  138. You ordered a pizza with no sauce and no cheese
  139. ```
  140. You can specify an option which functions as a flag but may also take a value (declared using square brackets).
  141. ```js
  142. const { program } = require('commander');
  143. program
  144. .option('-c, --cheese [type]', 'Add cheese with optional type');
  145. program.parse(process.argv);
  146. if (program.cheese === undefined) console.log('no cheese');
  147. else if (program.cheese === true) console.log('add cheese');
  148. else console.log(`add cheese type ${program.cheese}`);
  149. ```
  150. ```bash
  151. $ pizza-options
  152. no cheese
  153. $ pizza-options --cheese
  154. add cheese
  155. $ pizza-options --cheese mozzarella
  156. add cheese type mozzarella
  157. ```
  158. ### Custom option processing
  159. You may specify a function to do custom processing of option values. The callback function receives two parameters, the user specified value and the
  160. previous value for the option. It returns the new value for the option.
  161. This allows you to coerce the option value to the desired type, or accumulate values, or do entirely custom processing.
  162. You can optionally specify the default/starting value for the option after the function.
  163. ```js
  164. const { program } = require('commander');
  165. function myParseInt(value, dummyPrevious) {
  166. // parseInt takes a string and an optional radix
  167. return parseInt(value);
  168. }
  169. function increaseVerbosity(dummyValue, previous) {
  170. return previous + 1;
  171. }
  172. function collect(value, previous) {
  173. return previous.concat([value]);
  174. }
  175. function commaSeparatedList(value, dummyPrevious) {
  176. return value.split(',');
  177. }
  178. program
  179. .option('-f, --float <number>', 'float argument', parseFloat)
  180. .option('-i, --integer <number>', 'integer argument', myParseInt)
  181. .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)
  182. .option('-c, --collect <value>', 'repeatable value', collect, [])
  183. .option('-l, --list <items>', 'comma separated list', commaSeparatedList)
  184. ;
  185. program.parse(process.argv);
  186. if (program.float !== undefined) console.log(`float: ${program.float}`);
  187. if (program.integer !== undefined) console.log(`integer: ${program.integer}`);
  188. if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`);
  189. if (program.collect.length > 0) console.log(program.collect);
  190. if (program.list !== undefined) console.log(program.list);
  191. ```
  192. ```bash
  193. $ custom -f 1e2
  194. float: 100
  195. $ custom --integer 2
  196. integer: 2
  197. $ custom -v -v -v
  198. verbose: 3
  199. $ custom -c a -c b -c c
  200. [ 'a', 'b', 'c' ]
  201. $ custom --list x,y,z
  202. [ 'x', 'y', 'z' ]
  203. ```
  204. ### Required option
  205. You may specify a required (mandatory) option using `.requiredOption`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (say from environment). The method is otherwise the same as `.option` in format, taking flags and description, and optional default value or custom processing.
  206. ```js
  207. const { program } = require('commander');
  208. program
  209. .requiredOption('-c, --cheese <type>', 'pizza must have cheese');
  210. program.parse(process.argv);
  211. ```
  212. ```bash
  213. $ pizza
  214. error: required option '-c, --cheese <type>' not specified
  215. ```
  216. ### Version option
  217. The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.
  218. ```js
  219. program.version('0.0.1');
  220. ```
  221. ```bash
  222. $ ./examples/pizza -V
  223. 0.0.1
  224. ```
  225. You may change the flags and description by passing additional parameters to the `version` method, using
  226. the same syntax for flags as the `option` method. The version flags can be named anything, but a long name is required.
  227. ```js
  228. program.version('0.0.1', '-v, --vers', 'output the current version');
  229. ```
  230. ## Commands
  231. You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an action handler attached to the command, or as a stand-alone executable file (described in more detail later). The subcommands may be nested ([example](./examples/nestedCommands.js)).
  232. In the first parameter to `.command()` you specify the command name and any command arguments. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.
  233. You can use `.addCommand()` to add an already configured subcommand to the program.
  234. For example:
  235. ```js
  236. // Command implemented using action handler (description is supplied separately to `.command`)
  237. // Returns new command for configuring.
  238. program
  239. .command('clone <source> [destination]')
  240. .description('clone a repository into a newly created directory')
  241. .action((source, destination) => {
  242. console.log('clone command called');
  243. });
  244. // Command implemented using stand-alone executable file (description is second parameter to `.command`)
  245. // Returns `this` for adding more commands.
  246. program
  247. .command('start <service>', 'start named service')
  248. .command('stop [service]', 'stop named service, or all if no name supplied');
  249. // Command prepared separately.
  250. // Returns `this` for adding more commands.
  251. program
  252. .addCommand(build.makeBuildCommand());
  253. ```
  254. Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `true` for `opts.hidden` will remove the command from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified ([example](./examples/defaultCommand.js)).
  255. ### Specify the argument syntax
  256. You use `.arguments` to specify the arguments for the top-level command, and for subcommands they are usually included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required input. Square brackets (e.g. `[optional]`) indicate optional input.
  257. ```js
  258. const { program } = require('commander');
  259. program
  260. .version('0.1.0')
  261. .arguments('<cmd> [env]')
  262. .action(function (cmd, env) {
  263. cmdValue = cmd;
  264. envValue = env;
  265. });
  266. program.parse(process.argv);
  267. if (typeof cmdValue === 'undefined') {
  268. console.error('no command given!');
  269. process.exit(1);
  270. }
  271. console.log('command:', cmdValue);
  272. console.log('environment:', envValue || "no environment given");
  273. ```
  274. The last argument of a command can be variadic, and only the last argument. To make an argument variadic you
  275. append `...` to the argument name. For example:
  276. ```js
  277. const { program } = require('commander');
  278. program
  279. .version('0.1.0')
  280. .command('rmdir <dir> [otherDirs...]')
  281. .action(function (dir, otherDirs) {
  282. console.log('rmdir %s', dir);
  283. if (otherDirs) {
  284. otherDirs.forEach(function (oDir) {
  285. console.log('rmdir %s', oDir);
  286. });
  287. }
  288. });
  289. program.parse(process.argv);
  290. ```
  291. The variadic argument is passed to the action handler as an array.
  292. ### Action handler (sub)commands
  293. You can add options to a command that uses an action handler.
  294. The action handler gets passed a parameter for each argument you declared, and one additional argument which is the
  295. command object itself. This command argument has the values for the command-specific options added as properties.
  296. ```js
  297. const { program } = require('commander');
  298. program
  299. .command('rm <dir>')
  300. .option('-r, --recursive', 'Remove recursively')
  301. .action(function (dir, cmdObj) {
  302. console.log('remove ' + dir + (cmdObj.recursive ? ' recursively' : ''))
  303. })
  304. program.parse(process.argv)
  305. ```
  306. You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.
  307. ```js
  308. async function run() { /* code goes here */ }
  309. async function main() {
  310. program
  311. .command('run')
  312. .action(run);
  313. await program.parseAsync(process.argv);
  314. }
  315. ```
  316. A command's options on the command line are validated when the command is used. Any unknown options will be reported as an error.
  317. ### Stand-alone executable (sub)commands
  318. When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.
  319. Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`.
  320. You can specify a custom name with the `executableFile` configuration option.
  321. You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.
  322. ```js
  323. // file: ./examples/pm
  324. const { program } = require('commander');
  325. program
  326. .version('0.1.0')
  327. .command('install [name]', 'install one or more packages')
  328. .command('search [query]', 'search with optional query')
  329. .command('update', 'update installed packages', {executableFile: 'myUpdateSubCommand'})
  330. .command('list', 'list packages installed', {isDefault: true})
  331. .parse(process.argv);
  332. ```
  333. If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
  334. ## Automated help
  335. The help information is auto-generated based on the information commander already knows about your program. The default
  336. help option is `-h,--help`. ([example](./examples/pizza))
  337. ```bash
  338. $ node ./examples/pizza --help
  339. Usage: pizza [options]
  340. An application for pizzas ordering
  341. Options:
  342. -V, --version output the version number
  343. -p, --peppers Add peppers
  344. -c, --cheese <type> Add the specified type of cheese (default: "marble")
  345. -C, --no-cheese You do not want any cheese
  346. -h, --help display help for command
  347. ```
  348. A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show
  349. further help for the subcommand. These are effectively the same if the `shell` program has implicit help:
  350. ```bash
  351. shell help
  352. shell --help
  353. shell help spawn
  354. shell spawn --help
  355. ```
  356. ### Custom help
  357. You can display extra information by listening for "--help". ([example](./examples/custom-help))
  358. ```js
  359. program
  360. .option('-f, --foo', 'enable some foo');
  361. // must be before .parse()
  362. program.on('--help', () => {
  363. console.log('');
  364. console.log('Example call:');
  365. console.log(' $ custom-help --help');
  366. });
  367. ```
  368. Yields the following help output:
  369. ```Text
  370. Usage: custom-help [options]
  371. Options:
  372. -f, --foo enable some foo
  373. -h, --help display help for command
  374. Example call:
  375. $ custom-help --help
  376. ```
  377. ### .usage and .name
  378. These allow you to customise the usage description in the first line of the help. The name is otherwise
  379. deduced from the (full) program arguments. Given:
  380. ```js
  381. program
  382. .name("my-command")
  383. .usage("[global options] command")
  384. ```
  385. The help will start with:
  386. ```Text
  387. Usage: my-command [global options] command
  388. ```
  389. ### .help(cb)
  390. Output help information and exit immediately. Optional callback cb allows post-processing of help text before it is displayed.
  391. ### .outputHelp(cb)
  392. Output help information without exiting.
  393. Optional callback cb allows post-processing of help text before it is displayed.
  394. ### .helpInformation()
  395. Get the command help information as a string for processing or displaying yourself. (The text does not include the custom help
  396. from `--help` listeners.)
  397. ### .helpOption(flags, description)
  398. Override the default help flags and description.
  399. ```js
  400. program
  401. .helpOption('-e, --HELP', 'read more information');
  402. ```
  403. ### .addHelpCommand()
  404. You can explicitly turn on or off the implicit help command with `.addHelpCommand()` and `.addHelpCommand(false)`.
  405. You can both turn on and customise the help command by supplying the name and description:
  406. ```js
  407. program.addHelpCommand('assist [command]', 'show assistance');
  408. ```
  409. ## Custom event listeners
  410. You can execute custom actions by listening to command and option events.
  411. ```js
  412. program.on('option:verbose', function () {
  413. process.env.VERBOSE = this.verbose;
  414. });
  415. program.on('command:*', function (operands) {
  416. console.error(`error: unknown command '${operands[0]}'`);
  417. const availableCommands = program.commands.map(cmd => cmd.name());
  418. mySuggestBestMatch(operands[0], availableCommands);
  419. process.exitCode = 1;
  420. });
  421. ```
  422. ## Bits and pieces
  423. ### .parse() and .parseAsync()
  424. The first argument to `.parse` is the array of strings to parse. You may omit the parameter to implicitly use `process.argv`.
  425. If the arguments follow different conventions than node you can pass a `from` option in the second parameter:
  426. - 'node': default, `argv[0]` is the application and `argv[1]` is the script being run, with user parameters after that
  427. - 'electron': `argv[1]` varies depending on whether the electron application is packaged
  428. - 'user': all of the arguments from the user
  429. For example:
  430. ```js
  431. program.parse(process.argv); // Explicit, node conventions
  432. program.parse(); // Implicit, and auto-detect electron
  433. program.parse(['-f', 'filename'], { from: 'user' });
  434. ```
  435. ### Avoiding option name clashes
  436. The original and default behaviour is that the option values are stored
  437. as properties on the program, and the action handler is passed a
  438. command object with the options values stored as properties.
  439. This is very convenient to code, but the downside is possible clashes with
  440. existing properties of Command.
  441. There are two new routines to change the behaviour, and the default behaviour may change in the future:
  442. - `storeOptionsAsProperties`: whether to store option values as properties on command object, or store separately (specify false) and access using `.opts()`
  443. - `passCommandToAction`: whether to pass command to action handler,
  444. or just the options (specify false)
  445. ([example](./examples/storeOptionsAsProperties-action.js))
  446. ```js
  447. program
  448. .storeOptionsAsProperties(false)
  449. .passCommandToAction(false);
  450. program
  451. .name('my-program-name')
  452. .option('-n,--name <name>');
  453. program
  454. .command('show')
  455. .option('-a,--action <action>')
  456. .action((options) => {
  457. console.log(options.action);
  458. });
  459. program.parse(process.argv);
  460. const programOptions = program.opts();
  461. console.log(programOptions.name);
  462. ```
  463. ### TypeScript
  464. The Commander package includes its TypeScript Definition file.
  465. If you use `ts-node` and stand-alone executable subcommands written as `.ts` files, you need to call your program through node to get the subcommands called correctly. e.g.
  466. ```bash
  467. node -r ts-node/register pm.ts
  468. ```
  469. ### createCommand()
  470. This factory function creates a new command. It is exported and may be used instead of using `new`, like:
  471. ```js
  472. const { createCommand } = require('commander');
  473. const program = createCommand();
  474. ```
  475. `createCommand` is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally
  476. when creating subcommands using `.command()`, and you may override it to
  477. customise the new subcommand (examples using [subclass](./examples/custom-command-class.js) and [function](./examples/custom-command-function.js)).
  478. ### Node options such as `--harmony`
  479. You can enable `--harmony` option in two ways:
  480. - Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note Windows does not support this pattern.)
  481. - Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand process.
  482. ### Debugging stand-alone executable subcommands
  483. An executable subcommand is launched as a separate child process.
  484. If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al,
  485. the inspector port is incremented by 1 for the spawned subcommand.
  486. If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration.
  487. ### Override exit handling
  488. By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override
  489. this behaviour and optionally supply a callback. The default override throws a `CommanderError`.
  490. The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`. The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help
  491. is not affected by the override which is called after the display.
  492. ``` js
  493. program.exitOverride();
  494. try {
  495. program.parse(process.argv);
  496. } catch (err) {
  497. // custom processing...
  498. }
  499. ```
  500. ## Examples
  501. ```js
  502. const { program } = require('commander');
  503. program
  504. .version('0.1.0')
  505. .option('-C, --chdir <path>', 'change the working directory')
  506. .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
  507. .option('-T, --no-tests', 'ignore test hook');
  508. program
  509. .command('setup [env]')
  510. .description('run setup commands for all envs')
  511. .option("-s, --setup_mode [mode]", "Which setup mode to use")
  512. .action(function(env, options){
  513. const mode = options.setup_mode || "normal";
  514. env = env || 'all';
  515. console.log('setup for %s env(s) with %s mode', env, mode);
  516. });
  517. program
  518. .command('exec <cmd>')
  519. .alias('ex')
  520. .description('execute the given remote cmd')
  521. .option("-e, --exec_mode <mode>", "Which exec mode to use")
  522. .action(function(cmd, options){
  523. console.log('exec "%s" using %s mode', cmd, options.exec_mode);
  524. }).on('--help', function() {
  525. console.log('');
  526. console.log('Examples:');
  527. console.log('');
  528. console.log(' $ deploy exec sequential');
  529. console.log(' $ deploy exec async');
  530. });
  531. program.parse(process.argv);
  532. ```
  533. More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
  534. ## License
  535. [MIT](https://github.com/tj/commander.js/blob/master/LICENSE)
  536. ## Support
  537. Commander 5.x is fully supported on Long Term Support versions of Node, and is likely to work with Node 6 but not tested.
  538. (For versions of Node below Node 6, use Commander 3.x or 2.x.)
  539. The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.
  540. ### Commander for enterprise
  541. Available as part of the Tidelift Subscription
  542. The maintainers of Commander and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)