Avoid commander parser complaining when no arguments are present and just show helpInfo

I'm migrating a package from a much older version of commander (v2.20.3)

program.command(`install [pkg]`)
  .option(`-S, --save`, `Save to dependencies`)
  .option(`-D, --save-dev`, `Save to devDependencies`)
  .option(`--production`, `Will not install modules listed in devDependencies`)
  .option(`--test`, `Exit with code 1 if package limits like maxPackagesNumber or maxSizeBites exceeded`);

I'd like for the default (when calling the CLI with no arguments at all) to continue being the display of the help and no erring out, but currently it errs with:

.../npm-reflect/node_modules/.pnpm/commander@8.3.0/node_modules/commander/lib/command.js:142 const [, name, args] = nameAndArgs.match(/([^ ]+) (.)/);

I was able to get the mostly desired behavior by adding:

program.command('help', {isDefault: true})
  .action(() => {
  .command(`install [pkg]`)
  // ...

...but this seems to be polluting things in the help by listing a new "help" command. How can I avoid the parser complaining when no arguments are present yet without adding a new command?

1 answer

  • answered 2022-01-24 05:08 shadowspawn

    1. The default behaviour in latest Commander is to display the help if you have subcommands and do not specify a subcommand. Which sounds like what you want! Not sure how you are getting an error, you might want to open a Commander issue for help.

    2. In general, if you want some custom behaviour for no arguments then it may be simple and easy to check yourself before calling parse(). e.g.

    if (process.argv.length < 3)
      program.help(); // exits

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum