yargs .check()错误处理

abe*_*rob 1 command-line-interface node.js yargs

我正在使用yargs来验证用于数据加载助手库的cli参数。

我希望能够在允许运行脚本之前检查文件是否存在,对此我可以这样做fs.accessSync(filename, fs.R_OK);。但是,如果文件不存在,则消息传递只是将.check()函数显示为错误,而我要拦截,并声明该文件不存在(具有读取权限)。

那么,如何在错误返回时发送由.check()呈现的错误?

这是我的观点的要点:

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;
Run Code Online (Sandbox Code Playgroud)

以及返回的错误(如果不是可读文件):

Argument check failed: function (argv) {
  return fileExists(argv.f);
}
Run Code Online (Sandbox Code Playgroud)

我希望能够按照以下方式指定一些内容: Argument check failed: filepath is not a readable file

eep*_*lip 5

因此,在yargs 5.0.0中,当您返回非真实值时,它将打印整个输出。

Argument check failed: function (argv) {
  return fileExists(argv.f);
}
Run Code Online (Sandbox Code Playgroud)

如果抛出,则可以控制输出消息。

.check(function (argv) {
  if(fileExists(argv.f)) {
     return true;
  } else {
     throw(new Error('Argument check failed: filepath is not a readable file'));
  }
})
Run Code Online (Sandbox Code Playgroud)