简体   繁体   English

是否可以通过数组命令行 arguments nodejs?

[英]Is it possible to pass array command line arguments nodejs?

I want to create a script and to launch with yarn like this:我想创建一个脚本并像这样使用 yarn 启动:

yarn start arg1, arg2, arg3

it's work fine, I recover all arguments in:它工作正常,我在以下位置恢复了所有 arguments:

  const args = process.argv.slice(2);

But if I want to do:但如果我想这样做:

yarn start arg1, arg2, arg3, ['option1', 'option2']

it's not work, I got an error:这是行不通的,我收到一个错误:

zsh: no matches found: [option1]

I need an array of options sometimes and args can be infinite有时我需要一系列选项,args 可以是无限的

Thank you谢谢

process.argv will contain all arguments you pass, no matter how many there are. process.argv将包含您传递的所有参数,无论有多少。

The error you're getting is from your shell (zsh), not Node or Yarn – you need to quote arguments that have special characters such as [] :您收到的错误来自您的 shell (zsh),而不是 Node 或 Yarn – 您需要引用具有特殊字符的参数,例如[]

yarn start arg1 arg2 arg3 "['option1', 'option2']"

– here's a small example program to show the output: – 这是一个显示输出的小示例程序:

/tmp $ echo 'console.log(process.argv)' > args.js
/tmp $ node args.js arg1 arg2 arg3 "['option1', 'option2']"
[
  '/usr/local/bin/node',
  '/tmp/args.js',
  'arg1',
  'arg2',
  'arg3',
  "['option1', 'option2']"
]

I had same basic question - this pointed me in the right direction: https://stackoverflow.com/a/41402909/826308我有同样的基本问题 - 这为我指明了正确的方向: https://stackoverflow.com/a/41402909/826308

In my case I also needed to get to an array even if JSON.parse() failed so I used this:在我的例子中,即使 JSON.parse() 失败,我也需要访问一个数组,所以我使用了这个:

function stringToArray(str){
    var arr = [];
    if(str.indexOf('[',0) > -1 && str.indexOf(']',0) > -1){
    arr = JSON.parse(str);
  }else{
    arr.push(str);
  }
  return arr;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM