Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: Command line parsing with mutually exclusive arguments

I thought this should exist but it doesn't seem to be supported in any of the popular command line args parsing libraries.

I want my script to have a set of options that are exclusive of another option.

For example, here I use the -c option

$ node my_script.js -c "foo"

But here, the -c options doesn't make sense because I specified some different options.

$ node my_script.js -b "bar" -n 5

The following should be an error because -c is mutually exclusive to -b and -n

$ node my_script.js -b "bar" -n 5 -c "foo"

I know this exists in Python's argparse. I'm surprised I can't find it in the Node world.

like image 226
Sean Lynch Avatar asked Oct 19 '25 12:10

Sean Lynch


1 Answers

Commander.js has a convenient way of doing this through the Option.conflicts method. See the following example (adapted from here):

const { program, Option } = require('commander');
program
  .addOption(new Option('--cash').conflicts('credit'))
  .addOption(new Option('--credit'));

If you attempt to use both arguments, the program will fail and output the following message: error: option '--cash' cannot be used with option '--credit'

like image 136
cgoates Avatar answered Oct 21 '25 02:10

cgoates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!