Commander.js

The complete solution for node.js command-line interfaces, inspired by Ruby’s commander.

Build Status

Installation

  1. $ npm install commander

Option parsing

Options 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.

  1. #!/usr/bin/env node
  2. /**
  3. * Module dependencies.
  4. */
  5. var program = require('commander');
  6. program
  7. .version('0.0.1')
  8. .option('-p, --peppers', 'Add peppers')
  9. .option('-P, --pineapple', 'Add pineapple')
  10. .option('-b, --bbq', 'Add bbq sauce')
  11. .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
  12. .parse(process.argv);
  13. console.log('you ordered a pizza with:');
  14. if (program.peppers) console.log(' - peppers');
  15. if (program.pineapple) console.log(' - pineapple');
  16. if (program.bbq) console.log(' - bbq');
  17. console.log(' - %s cheese', program.cheese);

Short 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.

Automated —help

The help information is auto-generated based on the information commander already knows about your program, so the following --help info is for free:

  1. $ ./examples/pizza --help
  2. Usage: pizza [options]
  3. Options:
  4. -V, --version output the version number
  5. -p, --peppers Add peppers
  6. -P, --pineapple Add pineapple
  7. -b, --bbq Add bbq sauce
  8. -c, --cheese <type> Add the specified type of cheese [marble]
  9. -h, --help output usage information

Coercion

  1. function range(val) {
  2. return val.split('..').map(Number);
  3. }
  4. function list(val) {
  5. return val.split(',');
  6. }
  7. function collect(val, memo) {
  8. memo.push(val);
  9. return memo;
  10. }
  11. function increaseVerbosity(v, total) {
  12. return total + 1;
  13. }
  14. program
  15. .version('0.0.1')
  16. .usage('[options] <file ...>')
  17. .option('-i, --integer <n>', 'An integer argument', parseInt)
  18. .option('-f, --float <n>', 'A float argument', parseFloat)
  19. .option('-r, --range <a>..<b>', 'A range', range)
  20. .option('-l, --list <items>', 'A list', list)
  21. .option('-o, --optional [value]', 'An optional value')
  22. .option('-c, --collect [value]', 'A repeatable value', [])
  23. .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
  24. .parse(process.argv);
  25. console.log(' int: %j', program.integer);
  26. console.log(' float: %j', program.float);
  27. console.log(' optional: %j', program.optional);
  28. program.range = program.range || [];
  29. console.log(' range: %j..%j', program.range[0], program.range[1]);
  30. console.log(' list: %j', program.list);
  31. console.log(' collect: %j', program.collect);
  32. console.log(' verbosity: %j', program.verbose);
  33. console.log(' args: %j', program.args);

Custom help

You can display arbitrary -h, --help information by listening for “—help”. Commander will automatically exit once you are done so that the remainder of your program does not execute causing undesired behaviours, for example in the following executable “stuff” will not output when --help is used.

  1. #!/usr/bin/env node
  2. /**
  3. * Module dependencies.
  4. */
  5. var program = require('../');
  6. function list(val) {
  7. return val.split(',').map(Number);
  8. }
  9. program
  10. .version('0.0.1')
  11. .option('-f, --foo', 'enable some foo')
  12. .option('-b, --bar', 'enable some bar')
  13. .option('-B, --baz', 'enable some baz');
  14. // must be before .parse() since
  15. // node's emit() is immediate
  16. program.on('--help', function(){
  17. console.log(' Examples:');
  18. console.log('');
  19. console.log(' $ custom-help --help');
  20. console.log(' $ custom-help -h');
  21. console.log('');
  22. });
  23. program.parse(process.argv);
  24. console.log('stuff');

yielding the following help output:

  1. Usage: custom-help [options]
  2. Options:
  3. -h, --help output usage information
  4. -V, --version output the version number
  5. -f, --foo enable some foo
  6. -b, --bar enable some bar
  7. -B, --baz enable some baz
  8. Examples:
  9. $ custom-help --help
  10. $ custom-help -h

.outputHelp()

Output help information without exiting.

.help()

Output help information and exit immediately.

Links

License

(The MIT License)

Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.