Search code examples
typescriptcommand-line-interfacets-nodenode-commander

Accessing options variables in CLI commander Js action


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.


Solution

  • 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.)