Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unnamed parameter with commander.js

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.

like image 224
Golo Roden Avatar asked Jan 28 '13 05:01

Golo Roden


2 Answers

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.

like image 72
wlabs Avatar answered Sep 22 '22 12:09

wlabs


You get all the unnamed parameters through program.args. Add the following line to your example

console.log(' args: %j', program.args);

When you run your app with -p -b -c gouda arg1 arg2 you get

you ordered a pizza with:
- peppers
- bbq
- gouda cheese
args: ["arg1","arg2"]

Then you could write something like

copy args[0] to args[1] // just to give an idea
like image 44
zemirco Avatar answered Sep 22 '22 12:09

zemirco