Commander.js: [Question] How to get option name?

Created on 5 Mar 2021  路  7Comments  路  Source: tj/commander.js

From docs:

program
  .option('-d, --debug', 'output extra debugging')
  .option('-s, --small', 'small pizza size')
  .option('-p, --pizza-type <type>', 'flavour of pizza');

program.parse(process.argv);

const options = program.opts();
if (options.debug) console.log(options);
console.log('pizza details:');
if (options.small) console.log('- small pizza size');
if (options.pizzaType) console.log(`- ${options.pizzaType}`);

so, the question is how do know option pizza-type after parse will get from field pizzaType? Do commanderjs provide any function to get value pizzaType after bind option .option('-d, --debug', 'output extra debugging')?

Thanks!

bug

All 7 comments

The simplest answer is that the README says:

Multi-word options such as "--template-engine" are camel-cased, becoming program.opts().templateEngine etc.

For interest, there is a routine to get the property name, given an Option object.

program.option('-e, --example-of-long-option-name');
console.log(program.options[program.options.length - 1].attributeName());

const o = new Option('--camelCaseAlready');
console.log(o.attributeName());
$ node index.js
exampleOfLongOptionName
camelCaseAlready

Thank you!

@shadowspawn I use commanderjs with typescript and your resolution was not working.
image

Oh ok. .attributeName() got left out of the declarations, but it is public and could be added.

For interest, are you likely to use it in production code, or just when exploring how Commander is working?

I use for my project. Please update its @type, thanks!

attributeName included in Commander v7.2.0.

Was this page helpful?
0 / 5 - 0 ratings