我怎样才能parsing一个string到适当的参数child_process.spawn?

我希望能够采取一个命令string,例如:

some/script --option="Quoted Option" -d --another-option 'Quoted Argument' 

parsing成我可以发送给child_process.spawn

 spawn("some/script", ["--option=\"Quoted Option\"", "-d", "--another-option", "Quoted Argument"]) 

我发现的所有parsing库(例如minimist等)都是通过将其parsing为某种选项对象等来做太多的事情的 。我基本上想要Node的等价物来创buildprocess.argv

这看起来像是一个令人沮丧的漏洞,因为exec需要一个string,但是并不像spawn那样安全。 现在我正在用这个方法来解决这个问题:

 spawn("/bin/sh", ["-c", commandString]) 

但是,我不希望这样强烈地绑定到UNIX(理想情况下它也可以在Windows上工作)。 HALP?

标准方法(无库)

您不必将命令stringparsing为参数,在child_process.spawn命名的shell上有一个选项。

options.shell

如果为true ,则在shell中运行命令。
在UNIX上使用/bin/sh ,在Windows上使用cmd.exe

例:

 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) }) 

minimist-string包可能正是你正在寻找的。

这里有一些parsing你的示例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) 

这段代码输出这个 –

 { _: [ 'some/script' ], option: 'Quoted Option', d: true, 'another-option': 'Quoted Argument' }