Skip to content
Myr

Rework options description to clarify option types and custom processing

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by John Gee · committed by John Gee · parent 3e8bf54 · Browse files · 7 files+249 added−126 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+249 added−126 removed

  • other:+249 added−126 removed

7 files+249 added−126 removed

deleted:examples/coercion-46 removed
1#!/usr/bin/env node23/**4 * Module dependencies.5 */67var program = require('../');89function range(val) {10 return val.split('..').map(Number);11}1213function list(val) {14 return val.split(',');15}1617function collect(val, memo) {18 memo.push(val);19 return memo;20}2122function increaseVerbosity(v, total) {23 return total + 1;24}2526program27 .version('0.0.1')28 .usage('test')29 .option('-i, --integer <n>', 'An integer argument', parseInt)30 .option('-f, --float <n>', 'A float argument', parseFloat)31 .option('-r, --range <a>..<b>', 'A range', range)32 .option('-l, --list <items>', 'A list', list)33 .option('-o, --optional [value]', 'An optional value')34 .option('-c, --collect [value]', 'A repeatable value', collect, [])35 .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)36 .parse(process.argv);3738console.log(' int: %j', program.integer);39console.log(' float: %j', program.float);40console.log(' optional: %j', program.optional);41program.range = program.range || [];42console.log(' range: %j..%j', program.range[0], program.range[1]);43console.log(' list: %j', program.list);44console.log(' collect: %j', program.collect);45console.log(' verbosity: %j', program.verbose);46console.log(' args: %j', program.args);
added:examples/options-common.js+15 added
added:examples/options-custom-processing.js+35 added
added:examples/options-defaults.js+10 added
added:examples/options-flag-or-value.js+12 added
added:examples/options-negatable.js+10 added
modified:Readme.md+167 added-80 removed
1# Commander.js233[![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)
1 unmodified line
89 The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander). 10 [API documentation](http://tj.github.com/commander.js/)111312## Installation1314 $ npm install commander1518## Option parsing16## Declaring _program_ variable1720Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.18Commander exports a global object which is convenient for quick programs.19This is used in the examples in this README for brevity.2021```js23#!/usr/bin/env node22const program = require('commander');23program.version('0.0.1);24```2525/**26 * Module dependencies.27 */26For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.2728 ```js29var program = require('commander');29 const commander = require('commander');30 const program = new commander.Command;31 program.version('0.0.1);32 ```333435## Options3637Options 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.3839The options can be accessed as properties on the Command object. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. Multiple short flags may be combined as a single arg, for example `-abc` is equivalent to `-a -b -c`.4041### Common option types, boolean and value4243The 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.4445```js46const program = require('commander');4748program32 .version('0.1.0')33 .option('-p, --peppers', 'Add peppers')34 .option('-P, --pineapple', 'Add pineapple')35 .option('-b, --bbq-sauce', 'Add bbq sauce')36 .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')37 .parse(process.argv);49 .option('-d, --debug', 'output extra debugging')50 .option('-s, --small', 'small pizza size')51 .option('-p, --pizza-type <type>', 'flavour of pizza');5239console.log('you ordered a pizza with:');40if (program.peppers) console.log(' - peppers');41if (program.pineapple) console.log(' - pineapple');42if (program.bbqSauce) console.log(' - bbq');43console.log(' - %s cheese', program.cheese);53program.parse(process.argv);5455if (program.debug) console.log(program.opts());56console.log('pizza details:');57if (program.small) console.log('- small pizza size');58if (program.pizzaType) console.log(`- ${program.pizzaType}`);59```6046Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.61```bash62$ pizza-options -d63{ debug: true, small: undefined, pizzaType: undefined }64pizza details:65$ pizza-options -p66error: option `-p, --pizza-type <type>' argument missing67$ pizza-options -ds -p vegetarian68{ debug: true, small: true, pizzaType: 'vegetarian' }69pizza details:70- small pizza size71- vegetarian72$ pizza-options --pizza-type=cheese73pizza details:74- cheese75```7648Note that multi-word options starting with `--no` prefix negate the boolean value of the following word. For example, `--no-sauce` sets the value of `program.sauce` to false.77`program.parse(arguments)` processes the arguments, leaving any args not consumed by the options as the `program.args` array.7879### Default option value8081You can specify a default value for an option which takes a value.8283```js51#!/usr/bin/env node84const program = require('commander');8553/**54 * Module dependencies.55 */86program87 .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');8857var program = require('commander');89program.parse(process.argv);9091console.log(`cheese: ${program.cheese}`);92```9394```bash95$ pizza-options96cheese: blue97$ pizza-options --cheese stilton98cheese: stilton99```100101### Other option types, negatable boolean and flag|value102103You can specify a boolean option long name with a leading `no-` to make it true by default and able to be negated.104105106```js107const program = require('commander');108109program60 .option('--no-sauce', 'Remove sauce')110 .option('-n, --no-sauce', 'Remove sauce')111 .parse(process.argv);11263console.log('you ordered a pizza');64if (program.sauce) console.log(' with sauce');65else console.log(' without sauce');113if (program.sauce) console.log('you ordered a pizza with sauce');114else console.log('you ordered a pizza without sauce');115```11668To get string arguments from options you will need to use angle brackets <> for required inputs or square brackets [] for optional inputs. 117```bash118$ pizza-options119you ordered a pizza with sauce120$ pizza-options --sauce121error: unknown option `--sauce'122$ pizza-options --no-sauce123you ordered a pizza without sauce124```125You can specify an option which functions as a flag but may also take a value (declared using square brackets).12670e.g. ```.option('-m --myarg [myVar]', 'my super cool description')```12772Then to access the input if it was passed in.128```js129const program = require('commander');13074e.g. ```var myInput = program.myarg```131program132 .option('-c, --cheese [type]', 'Add cheese with optional type');13376**NOTE**: If you pass a argument without using brackets the example above will return true and not the value passed in.134program.parse(process.argv);135136if (program.cheese === undefined) console.log('no cheese');137else if (program.cheese === true) console.log('add cheese');138else console.log(`add cheese type ${program.cheese}`);139```14079## Version option141```bash142$ pizza-options143no cheese144$ pizza-options --cheese145add cheese146$ pizza-options --cheese mozzarella147add cheese type mozzarella148```149150### Custom option processing151152You may specify a function to do custom processing on options. The callback function receives two parameters, the user specified value and the 153previous value for the option. It returns the new value for the option.154155This allows you to coerce the option value to the desired type, or accumulate values, or do entirely custom processing.156157You can optionally specify the default/starting value for the option after the function.158159```js160const program = require('commander');161162function myParseInt(value, dummyPrevious) {163 // parseInt takes a string and an optional radix164 return parseInt(value);165}166167function increaseVerbosity(dummyValue, previous) {168 return previous + 1;169}170171function collect(value, previous) {172 return previous.concat([value]);173}174175function commaSeparatedList(value, dummyPrevious) {176 return value.split(',');177}178179program180 .option('-f, --float <number>', 'float argument', parseFloat)181 .option('-i, --integer <number>', 'integer argument', myParseInt)182 .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)183 .option('-c, --collect <value>', 'repeatable value', collect, [])184 .option('-l, --list <items>', 'comma separated list', commaSeparatedList)185;186187program.parse(process.argv);188189if (program.float !== undefined) console.log(`float: ${program.float}`);190if (program.integer !== undefined) console.log(`integer: ${program.integer}`);191if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`);192if (program.collect.length > 0) console.log(program.collect);193if (program.list !== undefined) console.log(program.list);194```195196```bash197$ custom -f 1e2198float: 100199$ custom --integer 2200integer: 2201$ custom -v -v -v202verbose: 3203$ custom -c a -c b -c c204[ 'a', 'b', 'c' ]205$ custom --list x,y,z206[ 'x', 'y', 'z' ]207```208209### Version option210211Calling the `version` implicitly adds the `-V` and `--version` options to the command.212When either of these options is present, the command prints the version number and exits.213214 $ ./examples/pizza -V
28 unmodified lines
243```244245A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.246117## Coercion118119```js120function range(val) {121 return val.split('..').map(Number);122}123124function list(val) {125 return val.split(',');126}127128function collect(val, memo) {129 memo.push(val);130 return memo;131}132133function increaseVerbosity(v, total) {134 return total + 1;135}136137program138 .version('0.1.0')139 .usage('[options] <file ...>')140 .option('-i, --integer <n>', 'An integer argument', parseInt)141 .option('-f, --float <n>', 'A float argument', parseFloat)142 .option('-r, --range <a>..<b>', 'A range', range)143 .option('-l, --list <items>', 'A list', list)144 .option('-o, --optional [value]', 'An optional value')145 .option('-c, --collect [value]', 'A repeatable value', collect, [])146 .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)147 .parse(process.argv);148149console.log(' int: %j', program.integer);150console.log(' float: %j', program.float);151console.log(' optional: %j', program.optional);152program.range = program.range || [];153console.log(' range: %j..%j', program.range[0], program.range[1]);154console.log(' list: %j', program.list);155console.log(' collect: %j', program.collect);156console.log(' verbosity: %j', program.verbose);157console.log(' args: %j', program.args);158```159247## Regular Expression248```js249program250 .version('0.1.0')
265 unmodified lines