javascript 当参数之一中有空格时,nodeJS child_process.spawn 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10941545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:33:39  来源:igfitidea点击:

nodeJS child_process.spawn does not work when one of the args has a space in it

javascriptnode.js

提问by giodamelio

I am trying to use the child_process.spawnfunction. The syntax is

我正在尝试使用该child_process.spawn功能。语法是

child_process.spawn(command, args=[], [options])

Whenever I include a space in any of the elements of the args array, the command simply emits the argument. Here is some code I used to test it

每当我在 args 数组的任何元素中包含一个空格时,该命令只会发出参数。这是我用来测试它的一些代码

var spawn = require("child_process").spawn

console.log("This works");
var watcher = spawn("ls", ["-l"]);
watcher.stdout.on('data', function(data) {
    process.stdout.write(data.toString());
});

console.log("This does not work");
watcher = spawn("ls", ["-l", "/path with space in it"]);
watcher.stdout.on('data', function(data) {
    process.stdout.write(data.toString());
});

Is this a bug in node? Do I need to escape the space?

这是节点中的错误吗?我需要逃离空间吗?

Edit: The above code is just an example. Here is the real code. Maybe is has to do with the pipes?

编辑:上面的代码只是一个例子。这是真正的代码。也许与管道有关?

watcher = spawn("supervisor", ["--extensions\ 'coffee|js|css|coffeekup'", "src/app.coffee"]);

回答by ma?ek

Don't put spaces in args, just use another argument in the array

不要在 中放置空格args,只需在数组中使用另一个参数

var watcher = spawn("supervisor", [
  "--extensions",
  "'coffee|js|css|coffeekup'",
  "src/app.coffee"
]);

A handy little shortcut I found if you want to get quick diagnostic output from your child processes is passing the {stdio: "inherit"}in options

一个方便的小捷径,我发现,如果你想从你的子进程得到快速诊断输出传递{stdio: "inherit"}options

var watcher = spawn("supervisor", [
  "--extensions",
  "'coffee|js|css|coffeekup'",
  "src/app.coffee"
], {stdio: "inherit"});

This way you can see whether everything is working properly right away.

通过这种方式,您可以立即查看是否一切正常。

Lastly, depending on where supervisoris installed, you might want to consider using the full path.

最后,根据supervisor安装位置,您可能需要考虑使用完整路径。

var watcher = spawn("/path/to/supervisor", ...);