-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add example for "global" options (#1708)
* Add example for common-options * Rename example so easier to find
- Loading branch information
1 parent
961c45e
commit 40e67bc
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
#!/usr/bin/env node | ||
|
||
// This example shows a couple of ways to add a "global" option to all of the subcommands. | ||
// The first approach is to use a subclass and add the option as the subcommand is created. | ||
// The second approach is to loop over the subcommands after they have been created. | ||
// | ||
// The code in this example assumes there is just one level of subcommands. | ||
// | ||
// (A different pattern for a "global" option is to add it to the root command, rather | ||
// than to the subcommand. That is not shown here.) | ||
|
||
// const { Command } = require('commander'); // (normal include) | ||
const { Command } = require('../'); // include commander in git clone of commander repo | ||
|
||
// Common options can be added when subcommands are created by using a custom subclass. | ||
// If the options are unsorted in the help, these will appear first. | ||
class MyRootCommand extends Command { | ||
createCommand(name) { | ||
const cmd = new Command(name); | ||
cmd.option('-v, --verbose', 'use verbose logging'); | ||
return cmd; | ||
} | ||
} | ||
|
||
const program = new MyRootCommand(); | ||
|
||
program.command('print') | ||
.option('--a4', 'Use A4 sized paper') | ||
.action((options) => { | ||
console.log('print options: %O', options); | ||
}); | ||
|
||
program.command('serve') | ||
.option('-p, --port <number>', 'port number for server') | ||
.action((options) => { | ||
console.log('serve options: %O', options); | ||
}); | ||
|
||
// Common options can be added manually after setting up program and subcommands. | ||
// If the options are unsorted in the help, these will appear last. | ||
program.commands.forEach((cmd) => { | ||
cmd.option('-d, --debug'); | ||
}); | ||
|
||
program.parse(); | ||
|
||
// Try the following: | ||
// node common-options.js --help | ||
// node common-options.js print --help | ||
// node common-options.js serve --help | ||
// node common-options.js serve --debug --verbose |