I'm passing an optional argument to a custom node script via the CLI as follows:
$ node myscript.js --sizes 10,20,30
myscript.js
utilizes process.argv to capture the --sizes
list as follows:
if (process.argv.indexOf('--sizes') !== -1) {
var sizeArgs = process.argv[process.argv.indexOf('--sizes') + 1];
console.log(sizeArgs); //--> 10,20,30
// ...
// using sizeArgs.split(',') later to create an array: ['10','20','30']
// plus some other logic to validate values are numbers etc etc.
}
Desired outcome is that console.log
prints the string 10,20,30
and that's what correctly happens when running the command (the one initially shown above) via:
- Mac OS - using either Terminal or iTerm
- Mac OSX - using either Terminal or iTerm
- Windows - using Command Prompt (cmd.exe)
Issue
When running the same command via Powershell on Windows console.log(sizeArgs)
prints 10
only.
So clearly the comma in the string 10,20,30
is somehow being interpreted as another argument, as the following test reveals:
// print process.argv
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});
Powershell prints:
...
2: --sizes
3: 10
4: 20
5: 30
For environments where the desired outcome is met the following prints:
...
2: --sizes
3: 10,20,30
Help
How can this be achieved cross platform considering the quirk in Powershell. Ultimately I need to obtain an array of sizes.
The reason I have chosen to use a comma [,
] as a separator for the --sizes
string is because another optional argument may also be provided (--outdir
which accepts a filepath as a string).
NOTE: I'm aware there are several package solutions yargs, args etc, etc, (which may or may not resolve the Powershell issue), however, I'm trying to avoid the additional dependency at this stage.