Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yargs - How to provide custom error msg for omitted positional argument

I can't find a way to properly configure positional arguments. I have this code:

#!/usr/bin/env node

const create = (argv) => {
  console.log('create component with name:', argv.name)
}

const createBuilder = (yargs) => {
  yargs.positional('name', {
    desc: 'Name of the new component',
  })
}

/* eslint-disable no-unused-expressions */
require('yargs')
  .command({
    command: 'create <name>',
    desc: 'Create a new component',
    builder: createBuilder,
    handler: create,
  })
  .demandCommand(1, 'A command is required')
  .help()
  .argv

and I would like to provide a custom error message in case the user doesn't specify a name after the create command.

It's not clear to me from the documentation how to do that, and while going through github issues I came across this comment (#928):

I recommend instead using demandCommand and demandOption (each of which are documented).

These allow you to configure positional arguments and flag arguments separately

I've tried all kinds of combinations with

.demandCommand(1, 'You need to provide name for the new component')

or

.demandOption('name', 'You need to provide name for the new component')

but without luck. Does anybody know how to do this?

like image 759
devboell Avatar asked Nov 16 '25 19:11

devboell


1 Answers

tl;dr - try making your command a default command by adding the string * or $0 to the start of your command name.

I've found that the positional arguments are only respected (ie: show up in the help menu and throw an error when a required positional isn't provided) when the positional argument is defined in a default command.

Here's an example of getting it to work with your code (note that you no longer have to use .demandCommand()):

require('yargs')
  .scriptName('cli-app')
  .command({
    command: '$0 create <name>',
    desc: 'Create a new component',
    builder: yargs => {
      yargs.positional('name', {
        desc: 'Name of the new component'
      });
    },
    handler: function(argv) {
      console.log('this is the handler function!');
    }
  })
  .help().argv;

Output (note the "Not enough non-option arguments: got 1, need at least 2" line at the end):

➞ node cli-app.js create                                                                                                                                       1 ↵
cli-app create <name>

Create a new component

Positionals:
  name  Name of the new component

Options:
  --version  Show version number                                       [boolean]
  --help     Show help                                                 [boolean]

Not enough non-option arguments: got 1, need at least 2
like image 144
Brian Zelip Avatar answered Nov 18 '25 10:11

Brian Zelip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!