- Install commander globally (yarn | pnpm | npm)
- Run the commander script using node
- Commander has built-in support for chaining program calls, adding options, descriptions, and parse writes.
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));
program.opts receives the options parameter.
Options#
Commander uses the .option() method to define options, and you can attach a description to each option. Each option can have a short option name (a single character after -) and a long option name (one or more words after --), separated by a comma, space, or |.
The parsed options can be accessed using the .opts() method on the Command object and will be passed to the command handler function.
For long options with multiple words, the option name will be converted to camel case. For example, the --template-engine option can be accessed using program.opts().templateEngine.
Options and their arguments can be separated by a space or combined into a single argument. Option arguments can be directly appended to the short option or followed by = after the long option.
serve -p 80
serve -p80
serve --port 80
serve --port=80
The -- can be used to mark the end of options, and any subsequent arguments will not be interpreted as options and can be used normally.
By default, the order of options on the command line is not fixed, and an option can be specified before or after other arguments.
When .opts() is not enough, there are other related methods available:
.optsWithGlobals() returns the merged local and global option values
.getOptionValue() and .setOptionValue() operate on the value of a single option
.getOptionValueSource() and .setOptionValueWithSource() include the source of the option value.
Common option types: boolean options and options with arguments#
There are two most commonly used types of options: boolean options, which do not require an argument, and options that can have arguments (declared using angle brackets after the option, e.g., --expect ). If a specific option and argument are not specified on the command line, they will be undefined.
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 size');
if (options.pizzaType) console.log(`- ${options.pizzaType}`);
For example:
$ pizza-options -p
error: option '-p, --pizza-type <type>' argument missing
$ pizza-options -d -s -p vegetarian
{ debug: true, small: true, pizzaType: 'vegetarian' }
pizza details:
- small pizza size
- vegetarian
$ pizza-options --pizza-type=cheese
pizza details:
- cheese
Multiple boolean short options can be combined after the dash and can be followed by a single option with a value. For example, -d -s -p cheese can be written as -ds -p cheese or even -dsp cheese.
Boolean options with expected option arguments are greedy and consume the argument regardless of its value. So --id -xyz will read -xyz as the option argument.
The arguments are processed using the program.parse(arguments) method, and any unused options will be stored in the program.args array. The arguments parameter is optional and defaults to process.argv.
Default values for options#
Add a third argument to the option method of program,
program
.option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');
program.parse();
console.log(`cheese: ${program.opts().cheese}`)
$ pizza-options
cheese: blue
$ pizza-options --cheese stilton
cheese: stilton
Other option types: negatable options and options with optional arguments#
You can define a boolean long option starting with no-. When this option is used on the command line, the corresponding option value will be set to false. If only the no- option is defined and the corresponding option without no- is not defined, the default value of the option will be set to true.
For example: nest g res mq --no-spec
If --foo is already defined, defining --no-foo will not change its default value.
For example:
program
.option('--no-sauce', 'Remove sauce')
.option('--cheese <flavour>', 'cheese flavour', 'mozzarella')
.option('--no-cheese', 'plain with no cheese')
.parse();
const options = program.opts();
const sauceStr = options.sauce ? 'sauce' : 'no sauce';
const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;
console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);
This means that by default, the value of options.sauce is true. The value of options.sauce will only be set to false if the --no-sauce option is explicitly used on the command line.
This is why the default value of sauce is true. If the user does not use any options related to sauce or only uses the --sauce option (even though it is not explicitly listed in the given option definition), the value of options.sauce will be true. The value will only be set to false if the user uses the --no-sauce option.
Let's see the printout:
$ pizza-options
You ordered a pizza with sauce and mozzarella cheese
$ pizza-options --sauce
error: unknown option '--sauce'
$ pizza-options --cheese=blue
You ordered a pizza with sauce and blue cheese
$ pizza-options --no-sauce --no-cheese
You ordered a pizza with no sauce and no cheese