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

标签 javascript node.js command-line node-commander

我正在使用 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()
}

关于javascript - Commander.js 在没有命令的情况下调用时显示帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44336656/

相关文章:

javascript - "float: right"没有把div放在右边

javascript - 如何在spectrum js输入框中附加多个颜色值?

JavaScript RegEx 语法高亮

javascript - 为什么 Magento 1.4 通过文件系统路径包含 javascript 文件?

命令行输入作为参数

ruby - 如何确定 Ruby 脚本的 shell 执行上下文?

mysql - Heroku 和 NodeJs - MySql 连接丢失 : The server closed the connection

node.js - 创建存档并在发送给客户端之前在其中添加文件

node.js - npm 错误! 404 未找到 : event-stream@3. 3.6

linux - Bash 脚本不继续读取文件的下一行