【问题标题】:Command Line Index命令行索引
【发布时间】:2021-06-03 04:51:34
【问题描述】:

我正在通过命令行发送以下文本,但不确定如何提取 -q 标记中的不同名称 命令: -s 127.0.0.1:3000 -q test1.pdf test2.pdf test3.pdf test4.pdf-v 7

发送的文件名数量可以改变

这就是我目前的解析方式
var s = process.argv.indexOf('-s') + 1;let files = process.argv.indexOf('-q') + 1; let version = process.argv.indexOf('-v') + 1;

let fileName = process.argv[files ].split(' ')

有什么建议可以尝试吗?

【问题讨论】:

    标签: javascript command-line-arguments argv


    【解决方案1】:

    您可以实现这个不同的基本解决方案,遍历参数并选择其中包含“.pdf”的参数。

    for (i of process.argv) {
        if (i.includes(".pdf")) {
            //i is your filename now, do something with it
            console.log(i);
        }
    }
    

    不同的是,如果您不仅有一种类型的文件扩展名,则可以对您已经猜测的内容应用更接近的解决方案,假设文件名总是包含在 @ 987654322@ 和 -v 标志:

    let fIdx = process.argv.indexOf('-q'); 
    let vIdx = process.argv.indexOf('-v'); 
    
    for (i of process.argv.slice(fIdx+1,vIdx)) {
        //i is your filename now, do something with it
        console.log(i)
    }
    

    【讨论】:

      【解决方案2】:

      通常对于命令行参数,如果每个 test*.pdf 文件都应该属于 -q 选项,我希望看到它们被列为:

      -q "test1.pdf,test2.pdf,test3.pdf,test4.pdf"
      

      -q test1.pdf -q test2.pdf -q test3.pdf -q test4.pdf
      

      除了是一种更传统的风格之外,这两种风格都会使逻辑更容易解析。

      另外,我建议您查看 yargs module (https://yargs.js.org/) 以解析参数。

      更新: 如果无法更改输入,那么我建议处理 args 列表,如果它以“-”字符开头,请记住该选项并继续将所有连续选项收集到该数组中,直到您到达另一个标志。

      一些粗略的代码:

      const opts = {}; // Hold all options
      const optionPattern = /^(?<Prefix>-{1,2}|\/)(?<Flag>.*)/; // Support various styles: -s, --s, /s
      let currFlag = 'Unknown'; // Bucket to hold any args not specifically marked
      
      for (const elem of process.argv) {
          const matchResult = optionPattern.exec(elem);
          if (matchResult) {
              currFlag = matchResult.groups.Flag;
          } else {
              opts[currFlag] = opts[currFlag] || []; // Create the array if this is the first one
              opts[currFlag].push(elem);
          }
      }
      
      console.log(`Options Received: ${JSON.stringify(opts, null, 4)}`);
      

      上面会输出:

      Options Received: {
      "Unknown": [
          "C:\\Program Files\\nodejs\\node.exe",
          "C:\\Projects\\NodeTestScripting\\TestScripts\\CommandLineArgs.js"
      ],
      "s": [
          "127.0.0.1:3000"
      ],
      "q": [
          "test1.pdf",
          "test2.pdf",
          "test3.pdf",
          "test4.pdf"
      ],
      "v": [
          "7"
      ]
      

      }

      【讨论】:

      • 感谢您的回复!不幸的是,有人要求我能够识别以该格式发送的文件。不太清楚如何去做
      猜你喜欢
      • 1970-01-01
      • 2011-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      • 2021-04-06
      相关资源
      最近更新 更多