How to use the command function from commander

Find comprehensive JavaScript commander.command code examples handpicked from public code repositorys.

commander.command is a method in the Commander.js library that creates a new command with a specified name and optional description, arguments, and options, to be parsed from the command-line arguments.

61
62
63
64
65
66
67
68
69
70
// Use spawn here so that we can pipe stdio from the command without buffering
spawn(
  shell,
  [
    '-c',
    program.command
      .replace(/\{event\}/gi, filePathContext)
      .replace(/\{path\}/gi, eventContext),
  ],
  {
fork icon0
star icon2
watch icon3

+ 3 other calls in file

23
24
25
26
27
28
29
30
31
32
});

var homedir = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
var pidFile = path.resolve(homedir, 'f2etest-local.pid');
var logFile = path.resolve(homedir, 'f2etest-local.log');
var runCommand = program.command('run')
    .description('run local proxy')
    .action(function(options){
        killOldProxy(function(){
            function onFinish(msg){
fork icon635
star icon0
watch icon237

+ 3 other calls in file

How does commander.command work?

commander.command is a method in the Commander.js library that creates a new command with a specified name and optional description, arguments, and options, to be parsed from the command-line arguments. When you call commander.command(name, [description], [options]), the function creates a new command with the specified name, and an optional description that will be displayed in the command-line help output. You can also specify any number of options for the command, using methods such as option, arguments, and alias, to define the options that the command accepts, the arguments it expects, and any aliases for the command or its options. Once you have defined one or more commands with commander.command, you can parse the command-line arguments using commander.parse(process.argv), which will automatically determine which command was invoked and call the appropriate callback function, passing in any specified arguments and options. In essence, commander.command provides a way to define custom commands with arguments and options, and to parse those commands from the command-line arguments, making it easy to build command-line interfaces for your Node.js applications.

49
50
51
52
53
54
55
56
57
58

for (const command of commands) {
  await Promise.resolve(command(program, client))
}

program.command('*', null, { noHelp: true }).action((cmd) => {
  console.error(`Invalid command: "${cmd}"`)
  console.error()
  program.outputHelp()
  suggestCommands(cmd)
fork icon99
star icon0
watch icon0

+ 9 other calls in file

20
21
22
23
24
25
26
27
28
29
if (!meta || !handle) {
  console.error(filename + ' 文件,不符合ckstyle命令文件规范')
  console.error('每一个命令必须包含 meta(命令描述) 和 handle(命令处理函数) 两个部分')
  return
}
var cmd = commander.command(meta.name)
commandNames.push(meta.name)
cmd.description(meta.description)
if (meta.options) {
  meta.options.forEach(function(op) {
fork icon8
star icon61
watch icon8

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const { Command } = require("commander");

const program = new Command();

program
  .command("hello [name]")
  .description("Say hello to a person")
  .option("-c, --capitalize", "Capitalize the name")
  .action((name, options) => {
    if (options.capitalize) {
      name = name.charAt(0).toUpperCase() + name.slice(1);
    }
    console.log(`Hello, ${name || "world"}!`);
  });

program.parse(process.argv);

In this example, we first import the Command class from the commander module, and create a new Command object. We then define a new command using the command method: hello [name]. This command expects an optional name argument, and has a description of "Say hello to a person". We also define an option -c, --capitalize, which, if specified, will capitalize the first letter of the name. Finally, we define an action function that will be called when the hello command is invoked. This function takes the name argument and options object as its arguments, and logs a greeting message to the console, optionally capitalizing the name based on the capitalize option. We then parse the command-line arguments using program.parse(process.argv). To invoke the hello command with an optional name argument and -c option, you would run the script with the following command: node script.js hello john -c. This would output: "Hello, John!"

12
13
14
15
16
17
18
19
20
21
const filePath = path.resolve(`${commandsPath}/${item}`);

if (fs.statSync(filePath).isFile()) {
  const parsed = path.parse(filePath);
  const commandName = parsed.name;
  const command = commander.command(commandName);

  try {
    require('./commands/' + commandName).createCommand(command);
  } catch (err) {
fork icon7
star icon7
watch icon17

+ 3 other calls in file

102
103
104
105
106
107
108
109
110
111
    // Get git branches and find matches
  })
  .action(function () {
    // Checkout a `git` branch
  });
var remote = program.command('remote');
remote
  // `git remote add origin git@github.com:...`
  // No possible tab completion here
  .command('add')
fork icon4
star icon26
watch icon4

+ 7 other calls in file

39
40
41
42
43
44
45
46
47
48
.action((program)=>{
  const options=program.opts();
  const { config, ver } = options;
  publisherUtils.doPublish(config,ver)
})
program.command('init')
.usage('init [options]')
.description('init config file')
.usage('init [options]')
.option('-f, --force', '',true)
fork icon0
star icon3
watch icon0

223
224
225
226
227
228
229
230
231
232
    }
    await updateConfig(options, program);
    require('./tasks/task-collections').serve();
  });

program.command('watch').action(async options => {
  options.watch = true;
  await updateConfig(options, program);
  require('./tasks/task-collections').watch();
});
fork icon44
star icon277
watch icon0

38
39
40
41
42
43
44
45
46
47
48
49


function daemon() {
    program.version(pjson.version, "-v, --version", "output the current version");
    program.option("-d, --debug", "turn on debug level logging", () => { log.debugging = true; });


    program.command("start", { isDefault: true })
        .description("start the portal service")
        .option("-p, --port <port>", "change the port the portal runs on")
        .action((command) => test(command.port, 0));

fork icon1
star icon2
watch icon0

11
12
13
14
15
16
17
18
19
20
21
22
    initCmd()
})




function initCmd() {
    program.command('start')
        .description('开启项目')
        .option('-n, --appName <string>', '服务名')
        .option('-c, --cwd <path>', '运行路径', './')
        .option('-s, --script <file>', '运行文件', 'app.js')
fork icon0
star icon2
watch icon0

+ 19 other calls in file

896
897
898
899
900
901
902
903
904
905
906
907
		console.log('');
	});


for (var name in commands) {
	
	var cmd = commander.command(name).description(commands[name].description).action(commands[name].action);
	
	cmd.option("-c, --config  <config>", "config file containing testbed configuration");


	if (commands[name].nodeFilterOptions) {
fork icon1
star icon0
watch icon0

+ 3 other calls in file

6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
  }));
}


try {
  program.version('1.0.0', '--version');
  program.command('word-counter <string>').description('Count number of words in a given string').action(string => {
    logger.info(`Your string has ${sentenceWordCounter(string)} word(s)`);
  });
  program.parse(process.argv);
} catch (error) {
fork icon0
star icon0
watch icon0

64
65
66
67
68
69
70
71
72
73
  .usage('<command> [options]')
  .storeOptionsAsProperties(false);

const defaultKeyFileName = 'dataset.key';

const init = cli.command('init');
addGlobalOptions(init);
addWalletLoadOptions(init);
init
  .option(...option.initDatasetFolders())
fork icon0
star icon0
watch icon12

+ 31 other calls in file

Other functions in commander

Sorted by popularity

function icon

commander.Option is the most popular function in commander (1786 examples)