Commander.js: Mandatory flags

Created on 16 Jan 2012  路  20Comments  路  Source: tj/commander.js

Commander supports required values for flags (.option('-f --foo <foo>', 'the value of foo)) but there doesn't appear to be a built-in way of making a flag itself required/mandatory.

Example:

var program = require('commander');

program
    .version('0.0.1')
    .option('-f --foo <foo>', 'Foo is required')
    .parse(process.argv);


console.log(program.foo);

Output:

$ node test.js -f bar
// outputs "bar", good

$ node test.js -f
// outputs "error: option `-f --foo <foo>' argument missing", good

$ node test.js
// outputs "undefined", not good; should output "error: required option `-f -foo <foo>' is missing" or similar

Most helpful comment

All 20 comments

I totally agree. Try the ls command with an invalid option:

$ ls -X
ls: illegal option -- X
usage: ls [-ABCFGHLOPRSTUWabcdefghiklmnopqrstuwx1] [file ...]

Seems like a reasonable requirement for commander.

+1

Having an asterisks at the end of the first option argument would be a good mandatory/required indicator.

+1

+1

Also, when a required parameter is missing, we should show the usage after the warning.

+1

+1

+1

+1

+1

I believe I mentioned this in a different issue, but it doesn't really make sense, that means the value is required, not the flag

@visionmedia do you mean to say that '--foo ' already implies that '--foo' is a _required_ arg? Also, what about command line args that are flags (and so do not have a value)? I have a feeling I am misunderstanding your response. Can you explain?

oh sorry I misread the original post, there was another issue which mentioned that --foo <bar> should imply that the flag should be required. Regarding this issue I think it could be doable but I don't think we could really come up with a great API for it. The required flags often vary as far as combinations go, so IMO it's leaky to try to come up with an API, I just plop in assert()s

If i get this correctly, there is not a way to have mandatory command line arguments still. This seems pretty important, especially given how devastating undefined values can be in a Javascript program

+1, why was this closed?

This is one of first things I needed from this package and it's still not here?

@vedmant Not yet. See #230 for the open issue.

See .requiredOption()

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mwittig picture mwittig  路  4Comments

0505gonzalez picture 0505gonzalez  路  3Comments

youurayy picture youurayy  路  5Comments

aminch picture aminch  路  3Comments

RoXioTD picture RoXioTD  路  4Comments