Skip to content
Myr

custom-command-class.js

This file

Path

examples/custom-command-class.js

48 lines · 1.4 KiB · JavaScript

Last changed by

Use standard import in examples (#2168)John Geebefore adoption41b12cf

History of this file

Take it

The walk stopped after 200 commits: lines older than c20284d point at it.

Add hooks for life cycle events: using .hook() (#1514)John Geebefore adoptionc20284d

line 1why, one step back
1#!/usr/bin/env node

Use standard import in examples (#2168)John Geebefore adoption41b12cf

line 2why, one step back
2const commander = require('commander');

Add hooks for life cycle events: using .hook() (#1514)John Geebefore adoptionc20284d

lines 3–48why, one step back
3
4// Use a class override to customise the command and its subcommands.56class CommandWithTrace extends commander.Command {7 createCommand(name) {8 const cmd = new CommandWithTrace(name);9 // Add an option to subcommands created using `.command()`10 cmd.option('-t, --trace', 'display extra information when run command');11 return cmd;12 }13};1415function inpectCommand(command) {16 // The option value is stored as property on command because we called .storeOptionsAsProperties()17 console.log(`Called '${command.name()}'`);18 console.log(`args: ${command.args}`);19 console.log('opts: %o', command.opts());20};2122const program = new CommandWithTrace('program')23 .option('-v, ---verbose')24 .action((options, command) => {25 inpectCommand(command);26 });2728program29 .command('serve [params...]')30 .option('-p, --port <number>', 'port number')31 .action((params, options, command) => {32 inpectCommand(command);33 });3435program36 .command('build <target>')37 .action((buildTarget, options, command) => {38 inpectCommand(command);39 });4041program.parse();4243// Try the following:44// node custom-command-class.js --help45// node custom-command-class.js serve --help46// node custom-command-class.js serve -t -p 80 a b c47// node custom-command-class.js build --help48// node custom-command-class.js build --trace foo