Commander.js: Multi Value Flags?

Created on 6 Oct 2013  路  8Comments  路  Source: tj/commander.js

Is there a way that i am missing to handle multi-value flags? Eg: foo --flag bar baz would output parse to program.flag = ['bar', 'baz']

If there isn't support, any opinion on the best option for this? Currently i am planning on using a string and splitting spaces, but foo --flag 'bar baz' is sub-optimal in my opinion.

Any thoughts would be appreciated, thank you

Most helpful comment

There is a Coercion section in documentation that contains simpler version of appender function:

function collect(val, memo) {
  memo.push(val);
  return memo;
}

program.option('-c, --collect [value]', 'A repeatable value', collect, []);

All 8 comments

I am looking for this actually, can't find a way to do it. Doesn't seem supported. Have you made any progress on it?

I'd suggest something like --foo bar,baz otherwise it's pretty ambiguous from a UX perspective as well

I would have to agree with @visionmedia

I couldn't really think of any good way, my main "issue" here was just to get some feedback on if this is a builtin feature or not. It sounds like not, so your best option is to use whichever method you prefer (string, comma split, etc)

I'm going to close this unless @visionmedia wants to actually implement native support for it (which may be overkill for such a fringe case)

For now, I've managed to do this using program.rawArgs but @visionmedia might be right for UX. Thanks to you two anyway.

How about foo --flag bar --flag baz, and an setting to make repeated assignments of a command option not override the previously set value but to append the array of values provided so far?

In that case,

  • calling foo would result in program.flag = [],
  • calling foo --flag bar respectively program.flag = ['bar'], and
  • foo --flag bar --flag baz in program.flag = ['bar', 'baz']

鈥nd, as a matter of fact, this can already be done using the formatter function of .option(鈥:

function appender(xs) {
  xs = xs || [];
  return function (x) {
    xs.push(x);
    return xs;
  }
}

program.option('--flag <value>', 'Pass multiple values for flag.', appender(), []);

I hope this helps!

It might make sense to point this out in the documentation, and maybe provide the above definition of appender() as part of the library.

There is a Coercion section in documentation that contains simpler version of appender function:

function collect(val, memo) {
  memo.push(val);
  return memo;
}

program.option('-c, --collect [value]', 'A repeatable value', collect, []);
Was this page helpful?
0 / 5 - 0 ratings

Related issues

hossamelmansy picture hossamelmansy  路  4Comments

RoXioTD picture RoXioTD  路  4Comments

mathiasbynens picture mathiasbynens  路  3Comments

shadowspawn picture shadowspawn  路  4Comments

jaredpetersen picture jaredpetersen  路  3Comments