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

2024-01-11

我在用着指挥官.js https://github.com/tj/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 and <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()
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐