Spa JS上的Spawn(Windows Server 2012)

fir*_*ire 12 windows spawn node.js windows-server-2012

当我通过Node运行时:

var spawn = require('child_process').spawn;

ls = spawn('ls', ['C:\\Users']);

ls.on('error', function (err) {
  console.log('ls error', err);
});

ls.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
});

ls.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
});

ls.on('close', function (code) {
    console.log('child process exited with code ' + code);
});
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

ls error { [Error: spawn ENOENT] code: 'ENOENT', errno: 'ENOENT', syscall: 'spawn' }
child process exited with code -1
Run Code Online (Sandbox Code Playgroud)

在Windows Server 2012上.有什么想法吗?

And*_*ndy 14

正如badsyntax指出的那样,只要你没有创建别名,ls就不存在于windows上.你会用'dir'.区别在于dir不是程序,而是windows shell中的命令(cmd.exe),所以你需要运行带有参数的'cmd'来运行dir并输出流.

var spawn = require('child_process').spawn
spawn('cmd', ['/c', 'dir'], { stdio: 'inherit'})
Run Code Online (Sandbox Code Playgroud)

通过使用'inherit',输出将通过管道传递到当前进程.


Gor*_*rky 13

从每个文档的节点 8 开始,您需要将 shell 选项设置为 true(默认情况下为 false)。

spawn('dir', [], { shell: true })
Run Code Online (Sandbox Code Playgroud)

文档在这里


bad*_*tax 12

(首先,确实ls存在于Windows上吗?)

我有一个类似的问题产生儿童过程一段时间后,我花了很长时间才弄清楚这样做的正确方法.

这是一些示例代码:

var spawn = require('child_process').spawn;
var cp = spawn(process.env.comspec, ['/c', 'command', '-arg1', '-arg2']);

cp.stdout.on("data", function(data) {
    console.log(data.toString());
});

cp.stderr.on("data", function(data) {
    console.error(data.toString());
});
Run Code Online (Sandbox Code Playgroud)

请查看此票证以解释该问题:https://github.com/joyent/node/issues/2318