JacobM
JacobM

Reputation: 11

yargs doesn't receive any arguments

I am trying to write a subcommand using yargs that takes in an argument, and following the documentation to the letter. However, the command itself acts like it doesn't receive any arguments, instead just using the default.

main.js:

require('yargs')()
    .commandDir(path.join(core.ROOT, 'cmds'), { extensions: ['cmd.js'], recurse: true })
    .wrap(null)
    .help()
    .alias('help', 'h')
    .version(false)
    .parse();

command.cmd.js:

module.exports = {
    command: 'my-command',
    desc: `Does something`,
    builder: {
        date: { type: 'string', alias: 'd', default: '' },
        start: { type: 'string', alias: 's', default: '' },
        end: { type: 'string', alias: 'e', default: '' },
    },
    async handler(argv) {
        console.log(require('util').inspect(argv, { depth: null }));
        ...
    }

The output for argv is:

  _: [ 'my-command', '2021-01-01', '2021-12-31' ],
  env: 'dev',
  date: '',
  d: '',
  start: '',
  s: '',
  end: '',
  e: '',
  '$0': 'src/main.js'
}

Upvotes: 1

Views: 1288

Answers (1)

randomuser5767124
randomuser5767124

Reputation: 329

In your code you aren't providing the user arguments,

require('yargs')()

.parse();

You probably want to provide process.argv.slice(2). like so:

require('yargs')(process.argv.slice(2))
...
.parse();

Not sure how you were able to verify the argv though, with the code you provided, it should always only give:

{ _: [], '$0': 'some_string' }

So maybe you did provide the arguments, and just forgot to show it in your example code.


The argv output had the dates as positional arguments:

{ _: [ 'my-command', '2021-01-01', '2021-12-31' ], ... }

It seems like you are trying to make those positional arguments as values for argv.start and argv.end. But you aren't telling yargs how to interpret positional arguments.

It should look something like this:

module.exports = {
    command: 'my-command [start] [end]',
    desc: `Does something`,
    builder: y => {
    return y.positional("start", {
        type: "string",
        alias: "s",
        default: ""
    });
    },
    async handler(argv) {
        console.log(require('util').inspect(argv, { depth: null }));
    }
}

Upvotes: 2

Related Questions