3

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")
Brady Holt
  • 2,844
  • 1
  • 28
  • 34

3 Answers3

9

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

Brady Holt
  • 2,844
  • 1
  • 28
  • 34
1

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.

Jason
  • 109
  • 4
0

How about this at the top?

if (process.argv.length < 3) {
   console.error("A file path is required");
   process.exit(1);
}
Arash Motamedi
  • 9,284
  • 5
  • 34
  • 43
  • I am trying to do this through yargs since I actually have other (optional) options that are available as well. yargs handles all those just fine and I would like to just configure it for this check as well. – Brady Holt Jan 11 '18 at 16:57