Brady Holt
Brady Holt

Reputation: 2924

yargs: Require at least one argument without a corresponding flag

I am building a Node CLI app that needs to be passed a single file as an argument.

For example:

myapp.js /Users/jdoe/my_file.txt

I know I can reference /Users/jdoe/my_file.txt through the _ object in yargs but how do I require that it be provided? I see the demandOption() method but I do not know how to demand options that do not have a corresponding flag (name).

I tried the following and it does not work:

.demandOption('_', "A file path is required")

Upvotes: 3

Views: 4345

Answers (3)

Jason
Jason

Reputation: 107

If you're satisfied with yargs and your solution, then by all means continue with what you're doing if you like! I would like to point out some alternatives. There's of course commander - a well-known cli creator tool. Commander seems to handle required arguments more gracefully than yargs. I have also created a cli creator tool to be (in my opinion) an improvement on the existing tools. The published tool is wily-cli, and it should be able to handle what you're wanting to do. For example...

const cli = require('wily-cli);

cli
  .parameter('file', true)
  .on('exec', (options, parameters, command) => {
    const file = parameters.file;
    // ...
  });

That would cover the example you provided. The true flag denotes that the parameter is required. If the parameter isn't provided to the command, it'll display an error saying the parameter is required.

Upvotes: 0

Brady Holt
Brady Holt

Reputation: 2924

I ended up using .demandCommand(1) which works!

Upvotes: 9

Arash Motamedi
Arash Motamedi

Reputation: 10682

How about this at the top?

if (process.argv.length < 3) {
   console.error("A file path is required");
   process.exit(1);
}

Upvotes: 0

Related Questions