2017-06-02 9 views
1

J'utilise commander.js pour écrire un programme node.js simple qui interagit avec une API. Tous les appels nécessitent l'utilisation de sous-commandes. Par exemple:Commander.js affiche de l'aide lorsqu'il est appelé sans aucune commande

apicommand get 

est appelé comme suit:

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); 

Ce que je veux faire maintenant afficher un message par défaut lorsque apicommand est appelée sans aucun sous-commandes. Tout comme lorsque vous appelez git sans sous-commande:

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

Check [ 'process.argv'] (https://nodejs.org/docs/latest/api/process.html#process_process_argv), il est un tableau qui contient les paramètres. –

Répondre

2

Vous pouvez faire quelque chose comme ceci en vérifiant quels arguments ont été reçus et si rien d'autre que node et <app>.js puis afficher le texte d'aide.

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

C'est ce que j'ai fini par faire. Merci! – toddg