2020-05-24 Two parameters and at least one required in yargs

I happen to write shell scripts in Node.JS quite often. They usually consume some kind of command-line arguments, and my library of choice to parse them is yargs.

Recently, I had a situation where there were two parameters and it was required that one of them is given. A bit surprisingly, yargs1 does not seem to have an option requiredAlternative or something that says “of the following two parameters, at least one must be given” (it has a conflicts method and option, either of which can be used to say e.g. “of these two parameters, at most one may be given”, though).

Happily, there is a simple way to enforce such a requirement due to the quite general “check” method. With it, you can enforce various non-trivial restrictions on the arguments, more complicated than “A is required” or “A conflicts with B​” Here is how you can use it.

const argv = require('yargs')
	.option('a', {
		demandOption: false,
	})
	.option('b', {
		demandOption: false,
	})
	.conflicts('a', 'b')
	.check((argv) => {
		if (!argv.a && !argv.b) {
			throw new Error('You must supply either --a or --b');
		} else {
			return true;
		}
	})
	.argv;

console.log(argv.a ? '--a supplied' : '--b supplied');

Note that the function supplied as the argument to check gets a second argument – an object whose keys are the option names and values are arrays of all possible aliases of each option. I have no idea what it could be used for, but there it is.

CategoryEnglish, CategoryBlog, CategoryJavaScript