【问题标题】:Write stdout to a div as program executes with Node-Webkit?在使用 Node-Webkit 执行程序时将标准输出写入 div?
【发布时间】:2015-02-18 12:23:28
【问题描述】:

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

问题是 stdout 仅在子应用程序退出后发送文本。

有没有办法在子应用程序运行时使用标准输出信息更新 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);
    }

});

【问题讨论】:

    标签: javascript windows node.js shell node-webkit


    【解决方案1】:

    您需要使用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/>');
    });
    

    【讨论】:

    • 它在大多数情况下确实有效,但是我似乎无法使用 jQuery 或用 brs 替换换行符 "stdout = stdout.replace(/(?:\r\n|\r| \n)/g, '
      ');"而在 proc.stdout.on('data', function(stdout)
    • 您可能需要在stdout 上致电toString()
    猜你喜欢
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多