Accessing options variables in CLI commander Js action

950 views Asked by At

I am pretty new to creating CLI apps. I am using ts-node and commander for this, however i am struggling to figure out how to access user passed in options in my command action.


program
  .version(version)
  .name(name)
  .option('-sm, --something', 'does something', false)
  .description(description);

program.command('clear-envirorment').action(() => {
  
  /// want to be able to see the passed in usage options here
  if (options.contains('-sm')) {
    // do something
  }

  (async () => {
    const userFeedback = await getPromptAnswers(CLEAR_ENV_QUESTIONS);
    if (userFeedback?.deleteAll) {
      cleanEnvirorment();
    }
  })();
});

Not sure if this is even something i should be doing, any help would be appreciated.

2

There are 2 answers

2
shadowspawn On

The action handler is passed the command-arguments and options for the command, and the command itself. In this simple example of an action handler there are just options and no command-arguments (positional arguments).

const { Command } = require('commander');
const program = new Command();

program
  .description('An application for pizza ordering')
  .option('-p, --peppers', 'Add peppers')
  .option('-c, --cheese <type>', 'Add the specified type of cheese', 'marble')
  .option('-C, --no-cheese', 'You do not want any cheese')
  .action(options => {
    console.log(options);
  })

program.parse();
$ node index.js -p -c cheddar
{ cheese: 'cheddar', peppers: true }

(Disclaimer: I am a maintainer of Commander.)

0
Jimmie Tyrrell On

An options object (of type any for TypeScript) gets appended as the last argument of the action. For example, in:

program
  .command('test <arg1> <arg2>')
  .option('-c, --count', 'Return a count')
  .option('-v, --verbose', 'Be verbose')
  .action((arg1, arg2, options) => {
    console.log(arg1, arg2, options)
  })

The following command

npm run cli test stack overflow -- --verbose --count

Will result in this output:

stack overflow { verbose: true, count: true }