UNPKG

38.6 kBMarkdownView Raw
1# Commander.js
2
3[![Build Status](https://github.com/tj/commander.js/workflows/build/badge.svg)](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22)
4[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
5[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
6[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)
7
8The complete solution for [node.js](http://nodejs.org) command-line interfaces.
9
10Read this in other languages: English | [简体中文](./Readme_zh-CN.md)
11
12- [Commander.js](#commanderjs)
13 - [Installation](#installation)
14 - [Quick Start](#quick-start)
15 - [Declaring _program_ variable](#declaring-program-variable)
16 - [Options](#options)
17 - [Common option types, boolean and value](#common-option-types-boolean-and-value)
18 - [Default option value](#default-option-value)
19 - [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue)
20 - [Required option](#required-option)
21 - [Variadic option](#variadic-option)
22 - [Version option](#version-option)
23 - [More configuration](#more-configuration)
24 - [Custom option processing](#custom-option-processing)
25 - [Commands](#commands)
26 - [Command-arguments](#command-arguments)
27 - [More configuration](#more-configuration-1)
28 - [Custom argument processing](#custom-argument-processing)
29 - [Action handler](#action-handler)
30 - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)
31 - [Life cycle hooks](#life-cycle-hooks)
32 - [Automated help](#automated-help)
33 - [Custom help](#custom-help)
34 - [Display help after errors](#display-help-after-errors)
35 - [Display help from code](#display-help-from-code)
36 - [.name](#name)
37 - [.usage](#usage)
38 - [.helpOption(flags, description)](#helpoptionflags-description)
39 - [.addHelpCommand()](#addhelpcommand)
40 - [More configuration](#more-configuration-2)
41 - [Custom event listeners](#custom-event-listeners)
42 - [Bits and pieces](#bits-and-pieces)
43 - [.parse() and .parseAsync()](#parse-and-parseasync)
44 - [Parsing Configuration](#parsing-configuration)
45 - [Legacy options as properties](#legacy-options-as-properties)
46 - [TypeScript](#typescript)
47 - [createCommand()](#createcommand)
48 - [Node options such as `--harmony`](#node-options-such-as---harmony)
49 - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)
50 - [Display error](#display-error)
51 - [Override exit and output handling](#override-exit-and-output-handling)
52 - [Additional documentation](#additional-documentation)
53 - [Support](#support)
54 - [Commander for enterprise](#commander-for-enterprise)
55
56For information about terms used in this document see: [terminology](./docs/terminology.md)
57
58## Installation
59
60```bash
61npm install commander
62```
63
64## Quick Start
65
66You write code to describe your command line interface.
67Commander looks after parsing the arguments into options and command-arguments,
68displays usage errors for problems, and implements a help system.
69
70Commander is strict and displays an error for unrecognised options.
71The two most used option types are a boolean option, and an option which takes its value from the following argument.
72
73Example file: [split.js](./examples/split.js)
74
75```js
76const { program } = require('commander');
77
78program
79 .option('--first')
80 .option('-s, --separator <char>');
81
82program.parse();
83
84const options = program.opts();
85const limit = options.first ? 1 : undefined;
86console.log(program.args[0].split(options.separator, limit));
87```
88
89```sh
90$ node split.js -s / --fits a/b/c
91error: unknown option '--fits'
92(Did you mean --first?)
93$ node split.js -s / --first a/b/c
94[ 'a' ]
95```
96
97Here is a more complete program using a subcommand and with descriptions for the help. In a multi-command program, you have an action handler for each command (or stand-alone executables for the commands).
98
99Example file: [string-util.js](./examples/string-util.js)
100
101```js
102const { Command } = require('commander');
103const program = new Command();
104
105program
106 .name('string-util')
107 .description('CLI to some JavaScript string utilities')
108 .version('0.8.0');
109
110program.command('split')
111 .description('Split a string into substrings and display as an array')
112 .argument('<string>', 'string to split')
113 .option('--first', 'display just the first substring')
114 .option('-s, --separator <char>', 'separator character', ',')
115 .action((str, options) => {
116 const limit = options.first ? 1 : undefined;
117 console.log(str.split(options.separator, limit));
118 });
119
120program.parse();
121```
122
123```sh
124$ node string-util.js help split
125Usage: string-util split [options] <string>
126
127Split a string into substrings and display as an array.
128
129Arguments:
130 string string to split
131
132Options:
133 --first display just the first substring
134 -s, --separator <char> separator character (default: ",")
135 -h, --help display help for command
136
137$ node string-util.js split --separator=/ a/b/c
138[ 'a', 'b', 'c' ]
139```
140
141More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
142
143## Declaring _program_ variable
144
145Commander exports a global object which is convenient for quick programs.
146This is used in the examples in this README for brevity.
147
148```js
149// CommonJS (.cjs)
150const { program } = require('commander');
151```
152
153For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.
154
155```js
156// CommonJS (.cjs)
157const { Command } = require('commander');
158const program = new Command();
159```
160
161```js
162// ECMAScript (.mjs)
163import { Command } from 'commander';
164const program = new Command();
165```
166
167```ts
168// TypeScript (.ts)
169import { Command } from 'commander';
170const program = new Command();
171```
172
173## Options
174
175Options 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 ('|').
176
177The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.
178
179Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.
180
181Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, followed by a single option taking a value (possibly followed by the value).
182For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`.
183
184You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.
185
186By default options on the command line are not positional, and can be specified before or after other arguments.
187
188There are additional related routines for when `.opts()` is not enough:
189
190- `.optsWithGlobals()` returns merged local and global option values
191- `.getOptionValue()` and `.setOptionValue()` work with a single option value
192- `.getOptionValueSource()` and `.setOptionValueWithSource()` include where the option value came from
193
194### Common option types, boolean and value
195
196The two most used option types are a boolean option, and an option which takes its value
197from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line.
198
199Example file: [options-common.js](./examples/options-common.js)
200
201```js
202program
203 .option('-d, --debug', 'output extra debugging')
204 .option('-s, --small', 'small pizza size')
205 .option('-p, --pizza-type <type>', 'flavour of pizza');
206
207program.parse(process.argv);
208
209const options = program.opts();
210if (options.debug) console.log(options);
211console.log('pizza details:');
212if (options.small) console.log('- small pizza size');
213if (options.pizzaType) console.log(`- ${options.pizzaType}`);
214```
215
216```bash
217$ pizza-options -p
218error: option '-p, --pizza-type <type>' argument missing
219$ pizza-options -d -s -p vegetarian
220{ debug: true, small: true, pizzaType: 'vegetarian' }
221pizza details:
222- small pizza size
223- vegetarian
224$ pizza-options --pizza-type=cheese
225pizza details:
226- cheese
227```
228
229`program.parse(arguments)` processes the arguments, leaving any args not consumed by the program options in the `program.args` array. The parameter is optional and defaults to `process.argv`.
230
231### Default option value
232
233You can specify a default value for an option.
234
235Example file: [options-defaults.js](./examples/options-defaults.js)
236
237```js
238program
239 .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');
240
241program.parse();
242
243console.log(`cheese: ${program.opts().cheese}`);
244```
245
246```bash
247$ pizza-options
248cheese: blue
249$ pizza-options --cheese stilton
250cheese: stilton
251```
252
253### Other option types, negatable boolean and boolean|value
254
255You can define a boolean option long name with a leading `no-` to set the option value to false when used.
256Defined alone this also makes the option true by default.
257
258If you define `--foo` first, adding `--no-foo` does not change the default value from what it would
259otherwise be.
260
261Example file: [options-negatable.js](./examples/options-negatable.js)
262
263```js
264program
265 .option('--no-sauce', 'Remove sauce')
266 .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')
267 .option('--no-cheese', 'plain with no cheese')
268 .parse();
269
270const options = program.opts();
271const sauceStr = options.sauce ? 'sauce' : 'no sauce';
272const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;
273console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);
274```
275
276```bash
277$ pizza-options
278You ordered a pizza with sauce and mozzarella cheese
279$ pizza-options --sauce
280error: unknown option '--sauce'
281$ pizza-options --cheese=blue
282You ordered a pizza with sauce and blue cheese
283$ pizza-options --no-sauce --no-cheese
284You ordered a pizza with no sauce and no cheese
285```
286
287You can specify an option which may be used as a boolean option but may optionally take an option-argument
288(declared with square brackets like `--optional [value]`).
289
290Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js)
291
292```js
293program
294 .option('-c, --cheese [type]', 'Add cheese with optional type');
295
296program.parse(process.argv);
297
298const options = program.opts();
299if (options.cheese === undefined) console.log('no cheese');
300else if (options.cheese === true) console.log('add cheese');
301else console.log(`add cheese type ${options.cheese}`);
302```
303
304```bash
305$ pizza-options
306no cheese
307$ pizza-options --cheese
308add cheese
309$ pizza-options --cheese mozzarella
310add cheese type mozzarella
311```
312
313For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).
314
315### Required option
316
317You 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.
318
319Example file: [options-required.js](./examples/options-required.js)
320
321```js
322program
323 .requiredOption('-c, --cheese <type>', 'pizza must have cheese');
324
325program.parse();
326```
327
328```bash
329$ pizza
330error: required option '-c, --cheese <type>' not specified
331```
332
333### Variadic option
334
335You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you
336can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments
337are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value
338is specified in the same argument as the option then no further values are read.
339
340Example file: [options-variadic.js](./examples/options-variadic.js)
341
342```js
343program
344 .option('-n, --number <numbers...>', 'specify numbers')
345 .option('-l, --letter [letters...]', 'specify letters');
346
347program.parse();
348
349console.log('Options: ', program.opts());
350console.log('Remaining arguments: ', program.args);
351```
352
353```bash
354$ collect -n 1 2 3 --letter a b c
355Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }
356Remaining arguments: []
357$ collect --letter=A -n80 operand
358Options: { number: [ '80' ], letter: [ 'A' ] }
359Remaining arguments: [ 'operand' ]
360$ collect --letter -n 1 -n 2 3 -- operand
361Options: { number: [ '1', '2', '3' ], letter: true }
362Remaining arguments: [ 'operand' ]
363```
364
365For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).
366
367### Version option
368
369The 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.
370
371```js
372program.version('0.0.1');
373```
374
375```bash
376$ ./examples/pizza -V
3770.0.1
378```
379
380You may change the flags and description by passing additional parameters to the `version` method, using
381the same syntax for flags as the `option` method.
382
383```js
384program.version('0.0.1', '-v, --vers', 'output the current version');
385```
386
387### More configuration
388
389You can add most options using the `.option()` method, but there are some additional features available
390by constructing an `Option` explicitly for less common cases.
391
392Example files: [options-extra.js](./examples/options-extra.js), [options-env.js](./examples/options-env.js)
393
394```js
395program
396 .addOption(new Option('-s, --secret').hideHelp())
397 .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))
398 .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']))
399 .addOption(new Option('-p, --port <number>', 'port number').env('PORT'))
400 .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat));
401```
402
403```bash
404$ extra --help
405Usage: help [options]
406
407Options:
408 -t, --timeout <delay> timeout in seconds (default: one minute)
409 -d, --drink <size> drink cup size (choices: "small", "medium", "large")
410 -p, --port <number> port number (env: PORT)
411 --donate [amount] optional donation in dollars (preset: 20)
412 -h, --help display help for command
413
414$ extra --drink huge
415error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.
416
417$ PORT=80 extra --donate
418Options: { timeout: 60, donate: 20, port: '80' }
419```
420
421### Custom option processing
422
423You may specify a function to do custom processing of option-arguments. The callback function receives two parameters,
424the user specified option-argument and the previous value for the option. It returns the new value for the option.
425
426This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing.
427
428You can optionally specify the default/starting value for the option after the function parameter.
429
430Example file: [options-custom-processing.js](./examples/options-custom-processing.js)
431
432```js
433function myParseInt(value, dummyPrevious) {
434 // parseInt takes a string and a radix
435 const parsedValue = parseInt(value, 10);
436 if (isNaN(parsedValue)) {
437 throw new commander.InvalidArgumentError('Not a number.');
438 }
439 return parsedValue;
440}
441
442function increaseVerbosity(dummyValue, previous) {
443 return previous + 1;
444}
445
446function collect(value, previous) {
447 return previous.concat([value]);
448}
449
450function commaSeparatedList(value, dummyPrevious) {
451 return value.split(',');
452}
453
454program
455 .option('-f, --float <number>', 'float argument', parseFloat)
456 .option('-i, --integer <number>', 'integer argument', myParseInt)
457 .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)
458 .option('-c, --collect <value>', 'repeatable value', collect, [])
459 .option('-l, --list <items>', 'comma separated list', commaSeparatedList)
460;
461
462program.parse();
463
464const options = program.opts();
465if (options.float !== undefined) console.log(`float: ${options.float}`);
466if (options.integer !== undefined) console.log(`integer: ${options.integer}`);
467if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);
468if (options.collect.length > 0) console.log(options.collect);
469if (options.list !== undefined) console.log(options.list);
470```
471
472```bash
473$ custom -f 1e2
474float: 100
475$ custom --integer 2
476integer: 2
477$ custom -v -v -v
478verbose: 3
479$ custom -c a -c b -c c
480[ 'a', 'b', 'c' ]
481$ custom --list x,y,z
482[ 'x', 'y', 'z' ]
483```
484
485## Commands
486
487You 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)).
488
489In the first parameter to `.command()` you specify the command name. You may append the command-arguments after the command name, or specify them separately using `.argument()`. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.
490
491You can use `.addCommand()` to add an already configured subcommand to the program.
492
493For example:
494
495```js
496// Command implemented using action handler (description is supplied separately to `.command`)
497// Returns new command for configuring.
498program
499 .command('clone <source> [destination]')
500 .description('clone a repository into a newly created directory')
501 .action((source, destination) => {
502 console.log('clone command called');
503 });
504
505// Command implemented using stand-alone executable file, indicated by adding description as second parameter to `.command`.
506// Returns `this` for adding more commands.
507program
508 .command('start <service>', 'start named service')
509 .command('stop [service]', 'stop named service, or all if no name supplied');
510
511// Command prepared separately.
512// Returns `this` for adding more commands.
513program
514 .addCommand(build.makeBuildCommand());
515```
516
517Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will
518remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other
519subcommand is specified ([example](./examples/defaultCommand.js)).
520
521### Command-arguments
522
523For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This
524is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands
525you can instead use the following method.
526
527To configure a command, you can use `.argument()` to specify each expected command-argument.
528You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.
529You can specify a default value for an optional command-argument.
530
531Example file: [argument.js](./examples/argument.js)
532
533```js
534program
535 .version('0.1.0')
536 .argument('<username>', 'user to login')
537 .argument('[password]', 'password for user, if required', 'no password given')
538 .action((username, password) => {
539 console.log('username:', username);
540 console.log('password:', password);
541 });
542```
543
544 The last argument of a command can be variadic, and only the last argument. To make an argument variadic you
545 append `...` to the argument name. A variadic argument is passed to the action handler as an array. For example:
546
547```js
548program
549 .version('0.1.0')
550 .command('rmdir')
551 .argument('<dirs...>')
552 .action(function (dirs) {
553 dirs.forEach((dir) => {
554 console.log('rmdir %s', dir);
555 });
556 });
557```
558
559There is a convenience method to add multiple arguments at once, but without descriptions:
560
561```js
562program
563 .arguments('<username> <password>');
564```
565
566#### More configuration
567
568There are some additional features available by constructing an `Argument` explicitly for less common cases.
569
570Example file: [arguments-extra.js](./examples/arguments-extra.js)
571
572```js
573program
574 .addArgument(new commander.Argument('<drink-size>', 'drink cup size').choices(['small', 'medium', 'large']))
575 .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute'))
576```
577
578#### Custom argument processing
579
580You may specify a function to do custom processing of command-arguments (like for option-arguments).
581The callback function receives two parameters, the user specified command-argument and the previous value for the argument.
582It returns the new value for the argument.
583
584The processed argument values are passed to the action handler, and saved as `.processedArgs`.
585
586You can optionally specify the default/starting value for the argument after the function parameter.
587
588Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js)
589
590```js
591program
592 .command('add')
593 .argument('<first>', 'integer argument', myParseInt)
594 .argument('[second]', 'integer argument', myParseInt, 1000)
595 .action((first, second) => {
596 console.log(`${first} + ${second} = ${first + second}`);
597 })
598;
599```
600
601### Action handler
602
603The action handler gets passed a parameter for each command-argument you declared, and two additional parameters
604which are the parsed options and the command object itself.
605
606Example file: [thank.js](./examples/thank.js)
607
608```js
609program
610 .argument('<name>')
611 .option('-t, --title <honorific>', 'title to use before name')
612 .option('-d, --debug', 'display some debugging')
613 .action((name, options, command) => {
614 if (options.debug) {
615 console.error('Called %s with options %o', command.name(), options);
616 }
617 const title = options.title ? `${options.title} ` : '';
618 console.log(`Thank-you ${title}${name}`);
619 });
620```
621
622If you prefer, you can work with the command directly and skip declaring the parameters for the action handler. The `this` keyword is set to the running command and can be used from a function expression (but not from an arrow function).
623
624Example file: [action-this.js](./examples/action-this.js)
625
626```js
627program
628 .command('serve')
629 .argument('<script>')
630 .option('-p, --port <number>', 'port number', 80)
631 .action(function() {
632 console.error('Run script %s on port %s', this.args[0], this.opts().port);
633 });
634```
635
636You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.
637
638```js
639async function run() { /* code goes here */ }
640
641async function main() {
642 program
643 .command('run')
644 .action(run);
645 await program.parseAsync(process.argv);
646}
647```
648
649A command's options and arguments on the command line are validated when the command is used. Any unknown options or missing arguments will be reported as an error. You can suppress the unknown option checks with `.allowUnknownOption()`. By default it is not an error to
650pass more arguments than declared, but you can make this an error with `.allowExcessArguments(false)`.
651
652### Stand-alone executable (sub)commands
653
654When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.
655Commander will search the files in the directory of the entry script for a file with the name combination `command-subcommand`, like `pm-install` or `pm-search` in the example below. The search includes trying common file extensions, like `.js`.
656You may specify a custom name (and path) with the `executableFile` configuration option.
657You may specify a custom search directory for subcommands with `.executableDir()`.
658
659You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.
660
661Example file: [pm](./examples/pm)
662
663```js
664program
665 .name('pm')
666 .version('0.1.0')
667 .command('install [name]', 'install one or more packages')
668 .command('search [query]', 'search with optional query')
669 .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' })
670 .command('list', 'list packages installed', { isDefault: true });
671
672program.parse(process.argv);
673```
674
675If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
676
677### Life cycle hooks
678
679You can add callback hooks to a command for life cycle events.
680
681Example file: [hook.js](./examples/hook.js)
682
683```js
684program
685 .option('-t, --trace', 'display trace statements for commands')
686 .hook('preAction', (thisCommand, actionCommand) => {
687 if (thisCommand.opts().trace) {
688 console.log(`About to call action handler for subcommand: ${actionCommand.name()}`);
689 console.log('arguments: %O', actionCommand.args);
690 console.log('options: %o', actionCommand.opts());
691 }
692 });
693```
694
695The callback hook can be `async`, in which case you call `.parseAsync` rather than `.parse`. You can add multiple hooks per event.
696
697The supported events are:
698
699- `preAction`: called before action handler for this command and its subcommands
700- `postAction`: called after action handler for this command and its subcommands
701
702The hook is passed the command it was added to, and the command running the action handler.
703
704## Automated help
705
706The help information is auto-generated based on the information commander already knows about your program. The default
707help option is `-h,--help`.
708
709Example file: [pizza](./examples/pizza)
710
711```bash
712$ node ./examples/pizza --help
713Usage: pizza [options]
714
715An application for pizza ordering
716
717Options:
718 -p, --peppers Add peppers
719 -c, --cheese <type> Add the specified type of cheese (default: "marble")
720 -C, --no-cheese You do not want any cheese
721 -h, --help display help for command
722```
723
724A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show
725further help for the subcommand. These are effectively the same if the `shell` program has implicit help:
726
727```bash
728shell help
729shell --help
730
731shell help spawn
732shell spawn --help
733```
734
735### Custom help
736
737You can add extra text to be displayed along with the built-in help.
738
739Example file: [custom-help](./examples/custom-help)
740
741```js
742program
743 .option('-f, --foo', 'enable some foo');
744
745program.addHelpText('after', `
746
747Example call:
748 $ custom-help --help`);
749```
750
751Yields the following help output:
752
753```Text
754Usage: custom-help [options]
755
756Options:
757 -f, --foo enable some foo
758 -h, --help display help for command
759
760Example call:
761 $ custom-help --help
762```
763
764The positions in order displayed are:
765
766- `beforeAll`: add to the program for a global banner or header
767- `before`: display extra information before built-in help
768- `after`: display extra information after built-in help
769- `afterAll`: add to the program for a global footer (epilog)
770
771The positions "beforeAll" and "afterAll" apply to the command and all its subcommands.
772
773The second parameter can be a string, or a function returning a string. The function is passed a context object for your convenience. The properties are:
774
775- error: a boolean for whether the help is being displayed due to a usage error
776- command: the Command which is displaying the help
777
778### Display help after errors
779
780The default behaviour for usage errors is to just display a short error message.
781You can change the behaviour to show the full help or a custom help message after an error.
782
783```js
784program.showHelpAfterError();
785// or
786program.showHelpAfterError('(add --help for additional information)');
787```
788
789```sh
790$ pizza --unknown
791error: unknown option '--unknown'
792(add --help for additional information)
793```
794
795You can also show suggestions after an error for an unknown command or option.
796
797```js
798program.showSuggestionAfterError();
799```
800
801```sh
802$ pizza --hepl
803error: unknown option '--hepl'
804(Did you mean --help?)
805```
806
807### Display help from code
808
809`.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.
810
811`.outputHelp()`: output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.
812
813`.helpInformation()`: get the built-in command help information as a string for processing or displaying yourself.
814
815### .name
816
817The command name appears in the help, and is also used for locating stand-alone executable subcommands.
818
819You may specify the program name using `.name()` or in the Command constructor. For the program, Commander will
820fallback to using the script name from the full arguments passed into `.parse()`. However, the script name varies
821depending on how your program is launched so you may wish to specify it explicitly.
822
823```js
824program.name('pizza');
825const pm = new Command('pm');
826```
827
828Subcommands get a name when specified using `.command()`. If you create the subcommand yourself to use with `.addCommand()`,
829then set the name using `.name()` or in the Command constructor.
830
831### .usage
832
833This allows you to customise the usage description in the first line of the help. Given:
834
835```js
836program
837 .name("my-command")
838 .usage("[global options] command")
839```
840
841The help will start with:
842
843```Text
844Usage: my-command [global options] command
845```
846
847### .helpOption(flags, description)
848
849By default every command has a help option. You may change the default help flags and description. Pass false to disable the built-in help option.
850
851```js
852program
853 .helpOption('-e, --HELP', 'read more information');
854```
855
856### .addHelpCommand()
857
858A help command is added by default if your command has subcommands. You can explicitly turn on or off the implicit help command with `.addHelpCommand()` and `.addHelpCommand(false)`.
859
860You can both turn on and customise the help command by supplying the name and description:
861
862```js
863program.addHelpCommand('assist [command]', 'show assistance');
864```
865
866### More configuration
867
868The built-in help is formatted using the Help class.
869You can configure the Help behaviour by modifying data properties and methods using `.configureHelp()`, or by subclassing using `.createHelp()` if you prefer.
870
871The data properties are:
872
873- `helpWidth`: specify the wrap width, useful for unit tests
874- `sortSubcommands`: sort the subcommands alphabetically
875- `sortOptions`: sort the options alphabetically
876
877There are methods getting the visible lists of arguments, options, and subcommands. There are methods for formatting the items in the lists, with each item having a _term_ and _description_. Take a look at `.formatHelp()` to see how they are used.
878
879Example file: [configure-help.js](./examples/configure-help.js)
880
881```js
882program.configureHelp({
883 sortSubcommands: true,
884 subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.
885});
886```
887
888## Custom event listeners
889
890You can execute custom actions by listening to command and option events.
891
892```js
893program.on('option:verbose', function () {
894 process.env.VERBOSE = this.opts().verbose;
895});
896```
897
898## Bits and pieces
899
900### .parse() and .parseAsync()
901
902The first argument to `.parse` is the array of strings to parse. You may omit the parameter to implicitly use `process.argv`.
903
904If the arguments follow different conventions than node you can pass a `from` option in the second parameter:
905
906- 'node': default, `argv[0]` is the application and `argv[1]` is the script being run, with user parameters after that
907- 'electron': `argv[1]` varies depending on whether the electron application is packaged
908- 'user': all of the arguments from the user
909
910For example:
911
912```js
913program.parse(process.argv); // Explicit, node conventions
914program.parse(); // Implicit, and auto-detect electron
915program.parse(['-f', 'filename'], { from: 'user' });
916```
917
918### Parsing Configuration
919
920If the default parsing does not suit your needs, there are some behaviours to support other usage patterns.
921
922By default program options are recognised before and after subcommands. To only look for program options before subcommands, use `.enablePositionalOptions()`. This lets you use
923an option for a different purpose in subcommands.
924
925Example file: [positional-options.js](./examples/positional-options.js)
926
927With positional options, the `-b` is a program option in the first line and a subcommand option in the second line:
928
929```sh
930program -b subcommand
931program subcommand -b
932```
933
934By default options are recognised before and after command-arguments. To only process options that come
935before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another program
936without needing to use `--` to end the option processing.
937To use pass through options in a subcommand, the program needs to enable positional options.
938
939Example file: [pass-through-options.js](./examples/pass-through-options.js)
940
941With pass through options, the `--port=80` is a program option in the first line and passed through as a command-argument in the second line:
942
943```sh
944program --port=80 arg
945program arg --port=80
946```
947
948By default the option processing shows an error for an unknown option. To have an unknown option treated as an ordinary command-argument and continue looking for options, use `.allowUnknownOption()`. This lets you mix known and unknown options.
949
950By default the argument processing does not display an error for more command-arguments than expected.
951To display an error for excess arguments, use`.allowExcessArguments(false)`.
952
953### Legacy options as properties
954
955Before Commander 7, the option values were stored as properties on the command.
956This was convenient to code but the downside was possible clashes with
957existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.
958
959```js
960program
961 .storeOptionsAsProperties()
962 .option('-d, --debug')
963 .action((commandAndOptions) => {
964 if (commandAndOptions.debug) {
965 console.error(`Called ${commandAndOptions.name()}`);
966 }
967 });
968```
969
970### TypeScript
971
972If 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.
973
974```bash
975node -r ts-node/register pm.ts
976```
977
978### createCommand()
979
980This factory function creates a new command. It is exported and may be used instead of using `new`, like:
981
982```js
983const { createCommand } = require('commander');
984const program = createCommand();
985```
986
987`createCommand` is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally
988when creating subcommands using `.command()`, and you may override it to
989customise the new subcommand (example file [custom-command-class.js](./examples/custom-command-class.js)).
990
991### Node options such as `--harmony`
992
993You can enable `--harmony` option in two ways:
994
995- Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note Windows does not support this pattern.)
996- Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand process.
997
998### Debugging stand-alone executable subcommands
999
1000An executable subcommand is launched as a separate child process.
1001
1002If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al,
1003the inspector port is incremented by 1 for the spawned subcommand.
1004
1005If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration.
1006
1007### Display error
1008
1009This routine is available to invoke the Commander error handling for your own error conditions. (See also the next section about exit handling.)
1010
1011As well as the error message, you can optionally specify the `exitCode` (used with `process.exit`)
1012and `code` (used with `CommanderError`).
1013
1014```js
1015program.error('Password must be longer than four characters');
1016program.error('Custom processing has failed', { exitCode: 2, code: 'my.custom.error' });
1017```
1018
1019### Override exit and output handling
1020
1021By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override
1022this behaviour and optionally supply a callback. The default override throws a `CommanderError`.
1023
1024The 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
1025is not affected by the override which is called after the display.
1026
1027```js
1028program.exitOverride();
1029
1030try {
1031 program.parse(process.argv);
1032} catch (err) {
1033 // custom processing...
1034}
1035```
1036
1037By default Commander is configured for a command-line application and writes to stdout and stderr.
1038You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.
1039
1040Example file: [configure-output.js](./examples/configure-output.js)
1041
1042```js
1043function errorColor(str) {
1044 // Add ANSI escape codes to display text in red.
1045 return `\x1b[31m${str}\x1b[0m`;
1046}
1047
1048program
1049 .configureOutput({
1050 // Visibly override write routines as example!
1051 writeOut: (str) => process.stdout.write(`[OUT] ${str}`),
1052 writeErr: (str) => process.stdout.write(`[ERR] ${str}`),
1053 // Highlight errors in color.
1054 outputError: (str, write) => write(errorColor(str))
1055 });
1056```
1057
1058### Additional documentation
1059
1060There is more information available about:
1061
1062- [deprecated](./docs/deprecated.md) features still supported for backwards compatibility
1063- [options taking varying arguments](./docs/options-taking-varying-arguments.md)
1064
1065## Support
1066
1067The current version of Commander is fully supported on Long Term Support versions of Node.js, and requires at least v12.20.0.
1068(For older versions of Node.js, use an older version of Commander.)
1069
1070The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.
1071
1072### Commander for enterprise
1073
1074Available as part of the Tidelift Subscription
1075
1076The 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)