Mic*_*igh 15 command-line parsing child-process node.js
我希望能够获取命令字符串,例如:
some/script --option="Quoted Option" -d --another-option 'Quoted Argument'
Run Code Online (Sandbox Code Playgroud)
并将其解析为我可以发送到的内容child_process.spawn:
spawn("some/script", ["--option=\"Quoted Option\"", "-d", "--another-option", "Quoted Argument"])
Run Code Online (Sandbox Code Playgroud)
我发现的所有解析库(例如最小化等)都通过将其解析为某种选项对象等来做太多.我基本上想要相当于Node process.argv首先要创建的东西.
这似乎是本机API中令人沮丧的漏洞,因为exec它接受一个字符串,但不能安全地执行spawn.现在我通过使用以下方式来解决这个问题:
spawn("/bin/sh", ["-c", commandString])
Run Code Online (Sandbox Code Playgroud)
但是,我不希望它如此强烈地与UNIX绑定(理想情况下它也适用于Windows).HALP?
chu*_*yik 13
您不必将命令字符串解析为参数,在child_process.spawn命名上有一个选项shell.
如果true,在shell中运行命令.
使用/bin/sh的UNIX和cmd.exeWindows上.
let command = `some_script --option="Quoted Option" -d --another-option 'Quoted Argument'`
let process = child_process.spawn(command, [], { shell: true }) // use `shell` option
process.stdout.on('data', (data) => {
console.log(data)
})
process.stderr.on('data', (data) => {
console.log(data)
})
process.on('close', (code) => {
console.log(code)
})
Run Code Online (Sandbox Code Playgroud)
该minimist-string软件包可能正是您正在寻找的。
这是一些解析示例字符串的示例代码 -
const ms = require('minimist-string')
const sampleString = 'some/script --option="Quoted Option" -d --another-option \'Quoted Argument\'';
const args = ms(sampleString);
console.dir(args)
Run Code Online (Sandbox Code Playgroud)
这段代码输出这个 -
{
_: [ 'some/script' ],
option: 'Quoted Option',
d: true,
'another-option': 'Quoted Argument'
}
Run Code Online (Sandbox Code Playgroud)