Commander.js: how to get specify option value?

Created on 25 Apr 2018  路  5Comments  路  Source: tj/commander.js

code

// mycmd.js
var program = require('commander')

program
  .option('-a, --aaa', 'option')
  .option('-b, --bbb', 'option')
  .option('-c, --ccc', 'option')
  .parse(process.argv);

call:

# may be follow to when user call:
mycmd -a aValue -b bValue -c cValue
# or
mycmd -b bValue -c cValue -a aValue 
# or
mycmd -c cValue -a aValue -b bValue 

how to get option value?
program.aorprogram.borprogram.calways get value is true/false,
i need user input value...

Most helpful comment

You need to write like this

  .option('-a, --aaa <aValue>', 'option')
  .option('-b, --bbb <bValue>', 'option')
  .option('-c, --ccc <cValue>', 'option')
  .parse(process.argv);

You can then access the value using program.aaa

All 5 comments

You need to write like this

  .option('-a, --aaa <aValue>', 'option')
  .option('-b, --bbb <bValue>', 'option')
  .option('-c, --ccc <cValue>', 'option')
  .parse(process.argv);

You can then access the value using program.aaa

e...3q...绐佺劧鍙戠幇鎴戜竴鐩寸敤閿欎簡...

To access to the specific value to have to use program.args which is an array of the options that you have added (is in order to the options).

You need to specify that the option takes a value. Expanding on the answer by @yausername

// mycmd.js
var program = require('commander')

program
  .option('-a, --aaa <value>', 'option')
  .option('-b, --bbb <value>', 'option')
  .option('-c, --ccc <value>', 'option')
  .parse(process.argv);

console.log(`aaa is ${program.aaa}`);
console.log(`bbb is ${program.bbb}`);
console.log(`ccc is ${program.ccc}`);
$ mycmd -b bValue -c cValue -a aValue 
aaa is aValue
bbb is bValue
ccc is cValue

This issue has not had any activity in over six months.

Feel free to open a new issue if it comes up again, with new information and renewed interest.

Thank you for your contributions.

Was this page helpful?
0 / 5 - 0 ratings