Files
commander.js/examples/custom-command-function.js
John Gee 8c3dd6ffe9 createCommand factory routine (#1191)
* Add factory method

* Fix return doc

* Can not use "this" for return type of createCommand

* Use return type of createCommand for subcommand

* Add mention of .command from .createCommand

* Remove trailing space

* Add examples for createCommand

* Explain example and make a little more realistic

* Add  comments pointing from .addCommand to .command

One of the downsides of extra ways of adding and creating commands is confusion with the more common way.

* Add createCommand to README

* Shift command/subcommand contrast

* Use single quotes in ts like in js, and clean up whitespace in new code
2020-03-02 19:31:43 +13:00

37 lines
985 B
JavaScript

#!/usr/bin/env node
// const commander = require('commander'); // (normal include)
const commander = require('../'); // include commander in git clone of commander repo
// Override createCommand directly to customise subcommands,
// in this example by adding --debug option.
const program = commander.createCommand();
// Customise subcommand creation
program.createCommand = (name) => {
const cmd = commander.createCommand(name);
cmd.option('-d,--debug', 'output options');
return cmd;
};
program
.command('serve')
.option('--port <port-number>', 'specify port number', 80)
.action((cmd) => {
if (cmd.debug) {
console.log('Options:');
console.log(cmd.opts());
console.log();
}
console.log(`Start serve on port ${cmd.port}`);
});
program.parse();
// Try the following:
// node custom-command-function.js help serve
// node custom-command-function.js serve --debug
// node custom-command-function.js serve --debug --port 8080