child_process spawn()中的通配符? [英] Wildcards in child_process spawn()?
问题描述
我想在node.js中执行带有"doSomething ./myfiles/*.csv"的命令.我想使用spawn而不是exec,因为这是某种监视过程,因此我需要stdout输出.
I want to execute a command like "doSomething ./myfiles/*.csv" with spawn in node.js. I want to use spawn instead of exec, because it is some kind of watch process and I need the stdout output.
我尝试过
var spawn = require('child_process').spawn;
spawn("doSomething", ["./myfiles/*.csv"]);
但是通配符* .csv不会被解释.
But then the wildcard *.csv will not interpreted.
使用spawn()时是否不能使用通配符?还有其他解决此问题的可能性吗?
Is it not possible to use wildcards when using spawn()? Are there other possibilities to solve this problem?
谢谢
托本
推荐答案
*
正在由外壳扩展,对于child_process.spawn
,参数将作为字符串传递,因此将永远无法正确扩展.这是spawn
的限制.您可以尝试使用child_process.exec
代替,它将允许Shell适当地扩展任何通配符:
The *
is being expanded by the shell, and for child_process.spawn
the arguments are coming through as strings so will never get properly expanded. It's a limitation of spawn
. You could try child_process.exec
instead, it will allow the shell to expand any wildcards properly:
var exec = require("child_process").exec;
var child = exec("doSomething ./myfiles/*.csv",function (err,stdout,stderr) {
// Handle result
});
如果由于某些原因确实需要使用spawn
,也许您可以考虑使用诸如 node-glob ?
If you really need to use spawn
for some reason perhaps you could consider expanding the wildcard file pattern yourself in Node with a lib like node-glob before creating the child process?
在Joyent Node核心代码中,我们可以观察到一种通过spawn
在shell中调用任意命令,同时保留完整的shell通配符扩展的方法:
In the Joyent Node core code we can observe an approach for invoking an arbitrary command in a shell via spawn
while retaining full shell wildcard expansion:
https://github.com/joyent/node/blob/937e2e351b2450cf1e9c4d8b3lib /child_process.js#L589
这是一些伪代码:
var child;
var cmd = "doSomething ./myfiles/*.csv";
if ('win32' === process.platform) {
child = spawn('cmd.exe', ['/s', '/c', '"' + cmd + '"'],{windowsVerbatimArguments:true} );
} else {
child = spawn('/bin/sh', ['-c', cmd]);
}
这篇关于child_process spawn()中的通配符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!