UNPKG

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