Search code examples
javascriptnode.jsecmascript-6yargs

Why are commands missing from this yargs script help page?


Can someone explain why the below script doesn't show the help for all commands?

test.js [command]

Commands:
  test.js list-spaces  List spaces

Options:
  --help     Show help                                                 [boolean]
  --version  Show version number                                       [boolean]

Notice the help for list-commands is missing for some reason.

#!/usr/bin/env node

'use strict'
const yargs = require("yargs");

yargs.command({
  command: 'list-spaces',
  describe: 'List spaces',
  type: 'boolean',
  handler: function(argv) {
    console.log('aaa');
  }
}).argv;

yargs.command({
  command: 'list-connectors',
  describe: 'List connectors',
  builder: {
    space: {
      describe: 'space',
      demandOption: true,
      type: 'string'
    },
  },
  handler: function(argv) {
    console.log(argv.space);
  }
}).argv;

Solution

  • Accessing .argv is what triggers the parsing (of process.args) and output generation. From the docs:

    Calling .parse() with no arguments is equivalent to calling .argv

    […]

    The rest of these methods below come in just before the terminating .argv or terminating .parse().

    You're accessing .argv twice for some reason. The first time, the second command is not yet registered. The second statement doesn't even run any more.