Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yargs .check() error handling

I'm using yargs to validate cli arguments for a data-loading helper lib.

I want to be able to check that a file exists before allowing the script to run, which I do with fs.accessSync(filename, fs.R_OK);. However, if the file does not exist, the messaging simply shows the .check() function as the error, whereas I want to intercept, and state that the file does not exist (with read permissions).

So how to I send an error to be presented by .check() on a false return?

Here is the gist of my yargs:

var path = {
  name: 'filepath',
  options: {
    alias: 'f',
    describe: 'provide json array file',
    demand: true,
  },
};

function fileExists(filename) {
  try {
    fs.accessSync(filename, fs.R_OK);
    return true;
  } catch (e) {
    return false;
  }
}

var argv = require('yargs')
  .usage('$0 [args]')
  .option(path.name, path.options)
  .check(function (argv) {
    return fileExists(argv.f);
  })
  .strict()
  .help('help')
  .argv;

and the returned error if not a readable file:

Argument check failed: function (argv) {
  return fileExists(argv.f);
}

I'd prefer to be able to specify something along the lines of: Argument check failed: filepath is not a readable file

like image 224
abenrob Avatar asked Jul 17 '16 09:07

abenrob


1 Answers

So in yargs 5.0.0 when you return a non-truthy value it will print that entire output.

Argument check failed: function (argv) {
  return fileExists(argv.f);
}

If you throw instead you can control the output message.

.check((argv) => {
  if (fileExists(argv.f)) {
     return true;
  }
  throw new Error('Argument check failed: filepath is not a readable file');
})
like image 143
eephillip Avatar answered Nov 13 '22 23:11

eephillip