# Commander.js
[![Build Status](https://github.com/tj/commander.js/workflows/build/badge.svg)](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22)
[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)
The complete solution for [node.js](http://nodejs.org) command-line interfaces.
Read this in other languages: English | [简体中文](./Readme_zh-CN.md)
- [Commander.js](#commanderjs)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Declaring _program_ variable](#declaring-program-variable)
- [Options](#options)
- [Common option types, boolean and value](#common-option-types-boolean-and-value)
- [Default option value](#default-option-value)
- [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue)
- [Required option](#required-option)
- [Variadic option](#variadic-option)
- [Version option](#version-option)
- [More configuration](#more-configuration)
- [Custom option processing](#custom-option-processing)
- [Commands](#commands)
- [Command-arguments](#command-arguments)
- [More configuration](#more-configuration-1)
- [Custom argument processing](#custom-argument-processing)
- [Action handler](#action-handler)
- [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)
- [Life cycle hooks](#life-cycle-hooks)
- [Automated help](#automated-help)
- [Custom help](#custom-help)
- [Display help after errors](#display-help-after-errors)
- [Display help from code](#display-help-from-code)
- [.name](#name)
- [.usage](#usage)
- [.helpOption(flags, description)](#helpoptionflags-description)
- [.addHelpCommand()](#addhelpcommand)
- [More configuration](#more-configuration-2)
- [Custom event listeners](#custom-event-listeners)
- [Bits and pieces](#bits-and-pieces)
- [.parse() and .parseAsync()](#parse-and-parseasync)
- [Parsing Configuration](#parsing-configuration)
- [Legacy options as properties](#legacy-options-as-properties)
- [TypeScript](#typescript)
- [createCommand()](#createcommand)
- [Node options such as `--harmony`](#node-options-such-as---harmony)
- [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)
- [Display error](#display-error)
- [Override exit and output handling](#override-exit-and-output-handling)
- [Additional documentation](#additional-documentation)
- [Support](#support)
- [Commander for enterprise](#commander-for-enterprise)
For information about terms used in this document see: [terminology](./docs/terminology.md)
## Installation
```bash
npm install commander
```
## Quick Start
You write code to describe your command line interface.
Commander looks after parsing the arguments into options and command-arguments,
displays usage errors for problems, and implements a help system.
Commander is strict and displays an error for unrecognised options.
The two most used option types are a boolean option, and an option which takes its value from the following argument.
Example file: [split.js](./examples/split.js)
```js
const { program } = require('commander');
program
.option('--first')
.option('-s, --separator <char>');
program.parse();
const options = program.opts();
const limit = options.first ? 1 : undefined;
console.log(program.args[0].split(options.separator, limit));
```
```sh
$ node split.js -s / --fits a/b/c
error: unknown option '--fits'
(Did you mean --first?)
$ node split.js -s / --first a/b/c
[ 'a' ]
```
Here 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).
Example file: [string-util.js](./examples/string-util.js)
```js
const { Command } = require('commander');
const program = new Command();
program
.name('string-util')
.description('CLI to some JavaScript string utilities')
.version('0.8.0');
program.command('split')
.description('Split a string into substrings and display as an array')
.argument('<string>', 'string to split')
.option('--first', 'display just the first substring')
.option('-s, --separator <char>', 'separator character', ',')
.action((str, options) => {
const limit = options.first ? 1 : undefined;
console.log(str.split(options.separator, limit));
});
program.parse();
```
```sh
$ node string-util.js help split
Usage: string-util split [options] <string>
Split a string into substrings and display as an array.
Arguments:
string string to split
Options:
--first display just the first substring
-s, --separator <char> separator character (default: ",")
-h, --help display help for command
$ node string-util.js split --separator=/ a/b/c
[ 'a', 'b', 'c' ]
```
More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
## Declaring _program_ variable
Commander exports a global object which is convenient for quick programs.
This is used in the examples in this README for brevity.
```js
// CommonJS (.cjs)
const { program } = require('commander');
```
For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.
```js
// CommonJS (.cjs)
const { Command } = require('commander');
const program = new Command();
```
```js
// ECMAScript (.mjs)
import { Command } from 'commander';
const program = new Command();
```
```ts
// TypeScript (.ts)
import { Command } from 'commander';
const program = new Command();
```
## Options
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 ('|').
The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.
Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.
An option and its option-argument can be separated by a space, or combined into the same argument. The option-argument can follow the short option directly or follow an `=` for a long option.
```bash
serve -p 80
serve -p80
serve --port 80
serve --port=80
```
You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.
By default options on the command line are not positional, and can be specified before or after other arguments.
There are additional related routines for when `.opts()` is not enough:
- `.optsWithGlobals()` returns merged local and global option values
- `.getOptionValue()` and `.setOptionValue()` work with a single option value
- `.getOptionValueSource()` and `.setOptionValueWithSource()` include where the option value came from
### Common option types, boolean and value
The two most used option types are a boolean option, and an option which takes its value
from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line.
Example file: [options-common.js](./examples/options-common.js)
```js
program
.option('-d, --debug', 'output extra debugging')
.option('-s, --small', 'small pizza size')
.option('-p, --pizza-type <type>', 'flavour of pizza');
program.parse(process.argv);
const options = program.opts();
if (options.debug) console.log(options);
console.log('pizza details:');
if (options.small) console.log('- small pizza