本文介绍了如何将字符串解析为child_process.spawn的适当参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用一个命令字符串,例如:

I want to be able to take a command string, for example:

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

并将其解析为可以发送给 child_process.spawn 的内容:

And parse it into something that I can send to child_process.spawn:

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

我发现的所有解析库(例如minimist等)在这里将其解析为某种选项对象的操作太多.我基本上想要与之等效的任何Node确实首先创建了 process.argv .

All of the parsing libraries I've found (e.g. minimist, etc.) do too much here by parsing it into some kind of options object, etc. I basically want the equivalent of whatever Node does to create process.argv in the first place.

这似乎是本机API中令人沮丧的漏洞,因为 exec 接受字符串,但执行起来不如 spawn 那样安全.现在,我正在使用以下方法来解决这个问题:

This seems like a frustrating hole in the native APIs since exec takes a string, but doesn't execute as safely as spawn. Right now I'm hacking around this by using:

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

但是,我不希望它与UNIX紧密地联系在一起(理想情况下也可以在Windows上使用).停顿吗?

However, I don't want this to be tied to UNIX so strongly (ideally it'd work on Windows too). Halp?

推荐答案

标准方法(无库)

您不必将命令字符串解析为参数, child_process.spawn 上有一个名为 shell 的选项.

Standard Method (no library)

You don't have to parse the command string into arguments, there's an option on child_process.spawn named shell.

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

If true, runs command inside of a shell.
Uses /bin/sh on UNIX, and cmd.exe on Windows.

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

这篇关于如何将字符串解析为child_process.spawn的适当参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 05:08