通常对于命令行参数,如果每个 test*.pdf 文件都应该属于 -q 选项,我希望看到它们被列为:
-q "test1.pdf,test2.pdf,test3.pdf,test4.pdf"
或
-q test1.pdf -q test2.pdf -q test3.pdf -q test4.pdf
除了是一种更传统的风格之外,这两种风格都会使逻辑更容易解析。
另外,我建议您查看 yargs module (https://yargs.js.org/) 以解析参数。
更新:
如果无法更改输入,那么我建议处理 args 列表,如果它以“-”字符开头,请记住该选项并继续将所有连续选项收集到该数组中,直到您到达另一个标志。
一些粗略的代码:
const opts = {}; // Hold all options
const optionPattern = /^(?<Prefix>-{1,2}|\/)(?<Flag>.*)/; // Support various styles: -s, --s, /s
let currFlag = 'Unknown'; // Bucket to hold any args not specifically marked
for (const elem of process.argv) {
const matchResult = optionPattern.exec(elem);
if (matchResult) {
currFlag = matchResult.groups.Flag;
} else {
opts[currFlag] = opts[currFlag] || []; // Create the array if this is the first one
opts[currFlag].push(elem);
}
}
console.log(`Options Received: ${JSON.stringify(opts, null, 4)}`);
上面会输出:
Options Received: {
"Unknown": [
"C:\\Program Files\\nodejs\\node.exe",
"C:\\Projects\\NodeTestScripting\\TestScripts\\CommandLineArgs.js"
],
"s": [
"127.0.0.1:3000"
],
"q": [
"test1.pdf",
"test2.pdf",
"test3.pdf",
"test4.pdf"
],
"v": [
"7"
]
}