I would like to write a CLI app that takes one optional argument.
import { Command } from 'commander';
const program = new Command();
program.argument('[a]');
program.action((a) => console.log(`a = ${a}`));
program.parse();
console.log(program.args);
If I run it with 0 or 1 arguments, it works as expected. However, I can't see a clean way to check that the whole command line was consumed by arguments. I'd like to error out if there are any trailing command line arguments. What's the best way to achieve that?
$ node no-trailing-args.js
a = undefined
[]
$ node no-trailing-args.js 1
a = 1
[ '1' ]
$ node no-trailing-args.js 1 2
a = 1
[ '1', '2' ]
$
By default it is not an error to pass more arguments than declared, but you can make this an error with .allowExcessArguments(false)
.
program.allowExcessArguments(false);