Commander.js 在没有命令的情况下调用时显示帮助

Commander.js display help when called with no commands

我正在使用 commander.js 编写一个与 API 交互的简单 node.js 程序。所有调用都需要使用子命令。例如:

apicommand get

调用如下:

program
  .version('1.0.0')
  .command('get [accountId]')
  .description('retrieves account info for the specified account')
  .option('-v, --verbose', 'display extended logging information')
  .action(getAccount);

我现在想做的是在没有任何子命令的情况下调用 apicommand 时显示默认消息。就像你在没有子命令的情况下调用 git 一样:

MacBook-Air:Desktop username$ git
usage: git [--version] [--help] [-C <path>] [-c name=value]
       [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
       [-p | --paginate | --no-pager] [--no-replace-objects] [--bare]
       [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
       <command> [<args>]

These are common Git commands used in various situations:

start a working area (see also: git help tutorial)
   clone      Clone a repository into a new directory
   init       Create an empty Git repository or reinitialize an existing one
...

您可以通过检查接收到的参数来执行类似的操作,如果除了 node<app>.js 之外没有其他参数,则显示帮助文本。

program
  .version('1.0.0')
  .command('get [accountId]')
  .description('retrieves account info for the specified account')
  .option('-v, --verbose', 'display extended logging information')
  .action(getAccount)
  .parse(process.argv)

if (process.argv.length < 3) {
  program.help()
}

当您尝试传递命令时,它会将命令存储在 process.argv 数组中。

您可以在代码末尾添加一个条件,例如 -:

if(process.argv.length  <= 2)
console.log(program.help());
else 
program.parse();

What I want to do now is display a default message when apicommand is called without any subcommands. Just like when you call git without a subcommand

Commander 5 及以上版本,如果您不使用子命令调用,帮助将自动显示。

(披露:我是 Commander 的维护者。)