当程序使用 Node-Webkit 执行时,将标准输出写入 div?

Write stdout to a div as program executes with Node-Webkit?

在我的 Node-Webkit 应用程序中,我使用 exec() 来执行子应用程序。应用程序将一些调试信息打印到 shell。

问题是标准输出仅在子应用程序退出后才发送文本。

有没有办法用标准输出信息更新 div 元素,因为子应用程序是 运行?

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

exec(executableFile,  function (error, stdout, stderr) {

    if (stdout) {
        // this only updates after the app exits
        console.log('stdout: ' + stdout);
        $('#console-output').append('stdout: ' + stdout +'<br/>');
    }

    if (error !== null) {
      console.log('exec error: ' + error);
    }

});

您需要使用 spawn 而不是 exec

Spawn 将数据作为流发回,因此您可以使用 stdout.on(fn)

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

var proc = spawn(executableFile);

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

proc.stdout.on('data', function(stdout) {
    $('#console-output').append('stdout: ' + stdout.toString() + '<br/>');
});