yegor256
yegor256

Reputation: 105053

How to process options before commands in commander.js?

This is my code:

const {program} = require('commander');
program
  .option('--foo')
  .command('bar').action((str, opts) => {
    console.log('bar!');
  })
program.parse();
if (program.opts().foo) {
  console.log('foo!');
}

I run it like node test.js --foo bar and it prints:

bar!
foo!

I want it to print foo! first. How can I do this?

Upvotes: 1

Views: 1078

Answers (1)

shadowspawn
shadowspawn

Reputation: 3825

What approach makes sense depends on your program, but here are three approaches: listener for option, lifecycle hook, and simple code. I suggest looking at the lifecycle hook first.

const {program} = require('commander');
program
  .option('--foo')
  .on('option:foo', () => console.log('foo detected'))
  .hook('preAction', () => console.log('about to call action'));

program
  .command('bar').action((opts) => {
    if (program.opts().foo) {
      console.log('found foo before checking for bar');
    }
    console.log('bar!');
  })
program.parse();
if (program.opts().foo) {
  console.log('foo!');
}
$ node index.js --foo bar
foo detected
about to call action
found foo before checking for bar
bar!
foo!

(Disclaimer: I am a maintainer of Commander.)

Upvotes: 3

Related Questions