I am trying to implement raw command line arguments in Node.js.
When I implement simple variables everything works
(node example.js variable)
But when I implement as an argument an array it doesn't work
(node example.js "['127.0.0.5', '127.0.0.3']" )
Full code:
if (process.argv.length <= 3) {
console.log("Usage: " + __filename + " SOME_PARAM");
process.exit(-1);
}
var variable = process.argv[2];
var array = process.argv[3];
console.log('Host: ' + variable);
console.log('array: ' + array);
Problem
Example of input of arguments ( node example.js variable "['127.0.0.5', '127.0.0.3']" )
How to pass the second argument ("['127.0.0.5', '127.0.0.3']") as an array rather than as a string (as it is now), so that later I might access array's n-th element (example array[0] = '127.0.0.5' )
SOLUTION
The input should be like ( '["127.0.0.5", "127.0.0.3"]' changing the quotes), and also we need to parse the argument as JSON.
if (process.argv.length <= 3) {
console.log("Usage: " + __filename + " SOME_PARAM");
process.exit(-1);
}
var variable = process.argv[2];
var array = JSON.parse(process.argv[4]);
console.log('Host: ' + variable);
console.log('array: ' + array);
console.log(array[1]