2017-06-02 61 views
1

我使用commander.js編寫一個簡單的node.js程序與API交互。所有呼叫都需要使用子命令。例如:Commander.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); 

我想現在要做的就是顯示默認的消息時apicommand被稱爲無子。

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 
... 
+0

檢查['process.argv'](https://nodejs.org/docs/latest/api/process.html#process_process_argv),它是一個包含參數的陣列。 –

回答

2

您可以通過檢查共收到什麼樣的參數,如果沒有其他比node做這樣的事情,並<app>.js然後顯示幫助文本:當你調用git無子就像。

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() 
} 
+0

這就是我最終做的。謝謝! – toddg