Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

commander.js : how to specify required cli argument

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?

like image 637
asking Avatar asked Jun 12 '14 01:06

asking


People also ask

How to create a help argument in commanderjs?

The convenient thing about this library is that, commanderJS will create a default help argument for you. There are different options and flavors you can choose from in commanderJS specific options, where you can choose how you want to customize your command. Finally, add process.agrv in the last line, so Commander can parse user inputs.

How to handle command line arguments in node?

Here are the node docs on handling command line args: process.argv is an array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

What are the option features of Commander?

This article provides a comprehensive hands-on for the various option features of Commander. When building a “good-old” command line interface (CLI) with NodeJS, the Commander package is of first choice. Commander offers you many features to design your CLI. The most comprehensive one is using options for a program or command.

Which array contains the command line arguments in JavaScript?

process.argv is an array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.


2 Answers

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')
like image 171
vinayr Avatar answered Oct 22 '22 19:10

vinayr


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
like image 1
Guillaume Brioudes Avatar answered Oct 22 '22 18:10

Guillaume Brioudes