yargs:需要至少一个没有相应标志的参数

yargs: Require at least one argument without a corresponding flag

我正在构建一个需要将单个文件作为参数传递的 Node CLI 应用程序。

例如:

myapp.js /Users/jdoe/my_file.txt

我知道我可以通过 yargs 中的 _ 对象引用 /Users/jdoe/my_file.txt,但我如何要求提供它?我看到 demandOption() 方法,但我不知道如何要求没有相应标志(名称)的选项。

我尝试了以下方法,但它不起作用:

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

顶部这个怎么样?

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

我最终使用了 .demandCommand(1),效果很好!

如果您对 yargs 和您的解决方案感到满意,那么如果您愿意,请务必继续您正在做的事情!我想指出一些替代方案。当然还有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,它应该能够处理你想做的事情。例如...

const cli = require('wily-cli);

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

这将涵盖您提供的示例。 true 标志表示该参数是必需的。如果没有为命令提供参数,它会显示一个错误,指出参数是必需的。