Commander by default will display an error for unknown options on the main command:
const program = require('commander');
program.parse(process.argv);
$ node index.js --silly
error: unknown option '--silly'
The relevant information from the Commander v4 README which covers subcommands is:
A command's options on the command line are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.
If you want to do extra handling yourself rather than exit when an unknown option is encountered, take a look at .exitOverride()
. For example:
const commander = require('commander');
const program = new commander.Command();
program.exitOverride(); // throw instead of exit
try {
program.parse(process.argv);
} catch (err) {
if (err.code === 'commander.unknownOption') {
console.log();
program.outputHelp();
}
}
$ node index.js --silly
error: unknown option '--silly'
Usage: index [options]
Options:
-h, --help output usage information