首页 > 解决方案 > 我将如何配置 yargs 以获取单个输入文件和可选的输出文件?

问题描述

我正在使用yargs来配置以下命令行选项:

Usage: myapp <source file> [destination file]

没有选项,没有命令等。只需读取一个文件路径和一个可选的写入路径。什么是 yarg 配置让我得到它给我所有好的文档?

似乎我需要使用选项或命令。我不能自己传递文件参数吗?

也看不到指挥官如何做到这一点。试图从 开始交易process.argv,但在第一关卡住了。

标签: javascriptcommand-line-interfaceyargs

解决方案


以下是如何获取第一个和第二个参数的示例:

var argv=require('yargs').argv
var source=argv._[0]
var dest=argv._[1]

甚至更好的方法:

const argv = require("yargs").command(
  "$0 <source file> [destination file]",
  "the default command",
  () => {},
  function({ sourcefile, destinationfile }) {
    console.log({ sourcefile, destinationfile })
  },
).argv

$0是默认命令。输出应该是:

myapp.js <source file> [destination file]

the default command

Options:
  --help     Show help                                                 [boolean]
  --version  Show version number                                       [boolean]

Not enough non-option arguments: got 0, need at least 1

学到更多:


推荐阅读