2013-08-20 50 views
10

當我通過節點運行此:菌種對節點JS(Windows Server 2012中)

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

我得到以下錯誤:

ls error { [Error: spawn ENOENT] code: 'ENOENT', errno: 'ENOENT', syscall: 'spawn' } 
child process exited with code -1 

在Windows Server 2012的任何想法?

回答

7

(首先,確實ls實際存在的窗口?)

我有一個類似的問題產卵子進程一會兒回來了,它花了年齡搞清楚這樣做的正確方法。

下面是一些示例代碼:

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

看一看這個票的問題的解釋:https://github.com/joyent/node/issues/2318

11

由於badsyntax指出,LS不存在於Windows,只要你沒有創建別名。你將使用'dir'。不同之處在於dir不是程序,而是windows shell(它是cmd.exe)中的一個命令,因此您需要運行帶參數的'cmd'來運行dir並輸出流。

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

通過使用'inherit',輸出將被傳送到當前進程。

1

這個問題已經有兩個工作答案,但我想再提一點,並澄清一些事情。

如果你不打算從你的命令返回大量的數據(超過200kB的多),你可以使用EXEC而不是產卵和更優雅的寫:

exec('dir [possible arguments]', (err, stdout, stderr) => { 
    console.log(`stdout: ${stdout}`) 
}) 

閱讀difference between spawn and exec。以確保它符合您的需求。

至於澄清,沒有必要通過{stdio:'inherit'}產卵,因爲它默認創建管道。從the documentation

By default, pipes for stdin, stdout and stderr are established between the parent Node.js process and the spawned child. It is possible to stream data through these pipes in a non-blocking way. Note, however, that some programs use line-buffered I/O internally. While that does not affect Node.js, it can mean that data sent to the child process may not be immediately consumed.

1

嗨下面的代碼爲我工作..

const spawn = require('child_process').spawn; 
const bat = spawn('cmd.exe', ['/c','calc.exe']); 

bat.stdout.on('data', (data) => { 
    console.log(data); 
}); 

bat.stderr.on('data', (data) => { 
    console.log(data); 
}); 

bat.on('closed', (code) => { 
alert(`Child exited with code ${code}`); 
});