node.jscommand-line-interfacenode-commander

Unnamed parameter with commander.js (positional arguments)


I am currently taking a look at commander.js as I want to implement a CLI using Node.js.

Using named parameters is easy, as the example of a "pizza" program shows:

program
  .version('0.0.1')
  .option('-p, --peppers', 'Add peppers')
  .option('-P, --pineapple', 'Add pineapple')
  .option('-b, --bbq', 'Add bbq sauce')
  .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
  .parse(process.argv);

Now, e.g., I can call the program using:

$ app -p -b

But what about an unnamed parameter? What if I want to call it using

$ app italian -p -b

? I think this is not so very uncommon, hence providing files for the cp command does not require you to use named parameters as well. It's just

$ cp source target

and not:

$ cp -s source -t target

How do I achieve this using commander.js?

And, how do I tell commander.js that unnamed parameters are required? E.g., if you take a look at the cp command, source and target are required.


Solution

  • With the present version of commander, it's possible to use positional arguments. See the docs on argument syntax for details, but using your cp example it would be something like:

    program
    .version('0.0.1')
    .arguments('<source> <target>')
    .action(function(source, target) {
        // do something with source and target
    })
    .parse(process.argv);
    

    This program will complain if both arguments are not present, and give an appropriate warning message.