2

I want to create a script and to launch with yarn like this :

yarn start arg1, arg2, arg3

it's work fine, I recover all arguments in :

  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

Thank you

Dams_al
  • 71
  • 1
  • 10

3 Answers3

3

process.argv will contain all arguments you pass, no matter how many there are.

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 []:

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']"
]
AKX
  • 152,115
  • 15
  • 115
  • 172
0

I had same basic question - this pointed me in the right direction: 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:

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

How can you parse this string "['option1', 'option2']" into array?

I don't have 50 reputation to answer Matt, however you can easily parse this array by surrounding it with JSON.parse.

Example:

    //assuming first argument (after the filename) will be an array
var argArray;
process.argv.forEach(function (arg, index, array)
{
        switch (index)
        {
                case 2:
                        argArray = arg;
        }
})

console.log(typeof(argArray), " var: ", argArray);

console.log(typeof(JSON.parse(argArray)), " var: ", argArray);

If you use this with an array argument written as such: "[\"test\", \"test\"]" you should get the following output from this program:

string  var:  ["test", "test"]
object  var:  ["test", "test"]

As you can see the string-formatted-array parsed as a JSON-string gets converted to an object which can be treated like an array.

Poseidon
  • 165
  • 1
  • 8