如果bat只运行一个终端,我们可以获得stdout,但如果打开一个新窗口,我们将失败。
var terminal = require('child_process').spawn('aa.bat');
console.log('Starting..terminal.pid.', terminal.pid, "process.pid", process.pid);
terminal.stdout.on('data', function(data) {
console.log('stdout:',data);
});
terminal.stderr.on('data', function(data) {
console.log('stderr:',data);
});
terminal.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
});
terminal.on('exit', function(code) {
console.log('exit code:', code, ' terinal.pid.', terminal.pid, "process.pid", process.pid);
console.log('child process', process.pid, 'exited with code ' + code);
});
假定这样的bat文件
start cmd
如果我们将其更改为
start /b cmd
这将不会打开一个新的终端,nodeJs将工作
答案 0 :(得分:0)
很难在Windows操作系统上从NodeJS获取另一个进程stdout,大多数情况下它会打开一个新的终端窗口。但你可以使用bash来启动它。
1.您可以从http://www.steve.org.uk/Software/bash/下载的bash.exe 然后代码可能是这样的:
var terminal = require('child_process');
function start() {
if (process.platform.trim() !== 'win32') {
terminal = terminal.spawn('bash');
console.log('This is not the win32 plantform ,please confirm the bash woking!');
} else {
terminal = terminal.spawn('./bash-2.03/bash.exe');
}
// !!!must append the ./
//terminal.stdin.write('./aa.exe');
terminal.stdin.write('./aa.bat');
terminal.stdin.end();
};
start();
terminal.stdout.on('data', function(data) {
console.log(data + "");
});
terminal.stdout.on('error', function(data) {
console.log('error:\n' + data);
});
terminal.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
});
terminal.on('exit', function(code) {
console.log('exit code:', code, ' terinal.pid.', terminal.pid, "process.pid", process.pid);
console.log('child process', process.pid, 'exited with code ' + code);
});