1 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個贊
Yargs 似乎可以非常可靠地解析字符串的參數(shù),而且它是相當(dāng)可配置的。
我想出了以下內(nèi)容,它似乎產(chǎn)生了您想要的輸出。但是,沒有用任何其他字符串對其進(jìn)行測試:
const parse = require("yargs-parser");
const argsFile = `
# Command line arguments
--download example.com
--pass
--no-fail
--output "C:\\Users\\User\\Desktop\\New Folder"
--binary-location 'C:\\Users\\Desktop\\New Folder\\executable program.exe'
`;
let parsedArguments = argsFile
.split(/\r?\n/)
.filter(
(argument) =>
!argument.startsWith("#") &&
!argument.startsWith(";") &&
!argument.startsWith("]")
)
.map((line) => {
return parse(line, {
string: true,
configuration: {
"boolean-negation": false,
"camel-case-expansion": false,
},
});
})
.map((ar) => {
delete ar._;
let properties = Object.keys(ar);
if (properties.length == 0) return [];
return [
"--" + properties[0],
typeof ar[properties[0]] == "boolean" ? "" : ar[properties[0]],
];
})
.filter((argument) => argument.length != 0);
let flatArgs = [].concat.apply([], parsedArguments).filter((i) => i != "");
console.dir(flatArgs);
產(chǎn)生以下結(jié)果:
[ '--download',
'example.com',
'--pass',
'--no-fail',
'--output',
'C:\\Users\\User\\Desktop\\New Folder',
'--binary-location',
'C:\\Users\\Desktop\\New Folder\\executable program.exe' ]
Yargs 解析器針對您的特定要求“過于積極地”解析字符串,這就是為什么我們必須通過有點(diǎn)反轉(zhuǎn)解析器所做的映射來進(jìn)行映射(以“--”開頭,忽略布爾值等)。然后,最后,我們必須“展平”數(shù)組,因?yàn)槊恳恍卸急唤馕龅剿约旱臄?shù)組中。
編輯:因此,如果我們也必須處理短參數(shù),那么 yargs 將不適合,因?yàn)槲覀冊诮馕龊鬅o法訪問原始字符串。我們可以使用 yarg 的內(nèi)部函數(shù)來標(biāo)記字符串,但是(我只需要將它轉(zhuǎn)換為 js):
function tokenizeArgString(argString) {
if (Array.isArray(argString)) {
return argString.map(e => typeof e !== 'string' ? e + '' : e);
}
argString = argString.trim();
let i = 0;
let prevC = null;
let c = null;
let opening = null;
const args = [];
for (let ii = 0; ii < argString.length; ii++) {
prevC = c;
c = argString.charAt(ii);
// split on spaces unless we're in quotes.
if (c === ' ' && !opening) {
if (!(prevC === ' ')) {
i++;
}
continue;
}
// don't split the string if we're in matching
// opening or closing single and double quotes.
if (c === opening) {
opening = null;
}
else if ((c === "'" || c === '"') && !opening) {
opening = c;
}
if (!args[i])
args[i] = '';
args[i] += c;
}
return args;
}
const argsFile = `
# Command line arguments
--download example.com
--pass
--no-fail
--output "C:\\Users\\User\\Desktop\\New Folder"
-a test
--binary-location 'C:\\Users\\Desktop\\New Folder\\executable program.exe'
`;
let parsedArguments = argsFile.split(/\r?\n/)
.filter(argument => (!argument.startsWith('#') && !argument.startsWith(';') && !argument.startsWith(']')))
.map(line => tokenizeArgString(line))
.filter(argument => argument.length != 0);
let flatArgsNoQuotes = [].concat.apply([], parsedArguments).map(args => args.replace(/['"]+/g, '')).filter(i => i != "");
console.dir(flatArgsNoQuotes)
添加回答
舉報(bào)