commander.js : how to specify required cli argument
Asked Answered
A

4

14

I'm using commander.js package for parsing command-line arguments: I'd like to make a flag non-optional, the API and tests in the git repo loosely mention making a flag required, but I usually need to be hit over the head with instructions.

Is it actually possible, and will the script throw if the requirement is not met?

Alevin answered 12/6, 2014 at 1:44 Comment(0)
T
24

I guess this is not supported by commander.js https://github.com/visionmedia/commander.js/issues/44

But you can do something like this in your program -

if (!program.myoption) 
  throw new Error('--myoption required')
Tupungato answered 12/6, 2014 at 4:42 Comment(1)
commander has program.requiredOption() to flag an option as required now.Euthanasia
A
7

It depends on how you write the arguments.

  • With <> it is required.
  • With [] it is not required.

See exemple.

const commander = require('commander')
    , program = new commander.Command()

program
   .command('autorecord')
   .argument('<title>', 'Title and file name of record') // is required
   .argument('[type]', 'Type of record. "undefined" by default') // is not required
Alvera answered 20/1, 2022 at 17:18 Comment(0)
U
0

2024 makeOptionMandatory

Per Commander 11.1+

const csv = new Option('--csv <name...>', 'CSV to read from').makeOptionMandatory()
p.command(...).addOption(csv)

... https://www.jsdocs.io/package/commander#Option.makeOptionMandatory

Urbina answered 26/6 at 13:55 Comment(0)
O
0

From Commander v4 you can use command.requiredOption(): https://github.com/tj/commander.js#required-option

Or as in another answer you can make an Option object and use option.makeOptionMandatory() and command.addOption().

Olsewski answered 1/7 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.