使用不同的 CLI 将命令行参数传递给节点跨平台
Passing command line arguments to node Cross Platform using different CLI
我正在通过 CLI 将可选参数传递给自定义节点脚本,如下所示:
$ node myscript.js --sizes 10,20,30
myscript.js
利用 process.argv 捕获 --sizes
列表如下:
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.
}
期望的结果是 console.log
打印字符串 10,20,30
并且当 运行 命令 (上面最初显示的那个) 来自:
- Mac OS - 使用 Terminal 或 iTerm
- Mac OSX - 使用 Terminal 或 iTerm
- Windows - 使用 命令提示符 (cmd.exe)
问题
当 运行 通过 Powershell 在 Windows 上执行相同命令时 console.log(sizeArgs)
仅打印 10
。
很明显,字符串 10,20,30
中的逗号以某种方式被解释为另一个参数,如下面的测试所示:
// print process.argv
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});
Powershell 打印:
...
2: --sizes
3: 10
4: 20
5: 30
对于满足预期结果的环境,打印如下:
...
2: --sizes
3: 10,20,30
帮助
考虑到 Powershell 中的怪癖,如何实现跨平台。最终我需要获得一个大小数组。
我之所以选择使用逗号 [,
] 作为 --sizes
字符串的分隔符是因为还可以提供另一个可选参数 (--outdir
接受文件路径作为字符串).
注意: 我知道有几个包解决方案 yargs, args 等等(可能会也可能不会解决 Powershell 问题),但是,我在这个阶段试图避免额外的依赖性。
通过确保将 --sizes
个值 10,20,30
放在双引号内解决了这个问题。
正如本 answer 中所建议的那样。
因此,跨平台 将包含逗号的参数传递给 node
的方法如下:
$ node myscript.js --sizes "10,20,30"
重新测试
现在,原始问题中使用的测试在所有 platforms/environments 个测试中打印如下:
...
2: --sizes
3: 10,20,30
我正在通过 CLI 将可选参数传递给自定义节点脚本,如下所示:
$ node myscript.js --sizes 10,20,30
myscript.js
利用 process.argv 捕获 --sizes
列表如下:
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.
}
期望的结果是 console.log
打印字符串 10,20,30
并且当 运行 命令 (上面最初显示的那个) 来自:
- Mac OS - 使用 Terminal 或 iTerm
- Mac OSX - 使用 Terminal 或 iTerm
- Windows - 使用 命令提示符 (cmd.exe)
问题
当 运行 通过 Powershell 在 Windows 上执行相同命令时 console.log(sizeArgs)
仅打印 10
。
很明显,字符串 10,20,30
中的逗号以某种方式被解释为另一个参数,如下面的测试所示:
// print process.argv
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});
Powershell 打印:
...
2: --sizes
3: 10
4: 20
5: 30
对于满足预期结果的环境,打印如下:
...
2: --sizes
3: 10,20,30
帮助
考虑到 Powershell 中的怪癖,如何实现跨平台。最终我需要获得一个大小数组。
我之所以选择使用逗号 [,
] 作为 --sizes
字符串的分隔符是因为还可以提供另一个可选参数 (--outdir
接受文件路径作为字符串).
注意: 我知道有几个包解决方案 yargs, args 等等(可能会也可能不会解决 Powershell 问题),但是,我在这个阶段试图避免额外的依赖性。
通过确保将 --sizes
个值 10,20,30
放在双引号内解决了这个问题。
正如本 answer 中所建议的那样。
因此,跨平台 将包含逗号的参数传递给 node
的方法如下:
$ node myscript.js --sizes "10,20,30"
重新测试
现在,原始问题中使用的测试在所有 platforms/environments 个测试中打印如下:
...
2: --sizes
3: 10,20,30