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
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']"
]
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.