【问题标题】:Reading from a stdout in real time using node.js使用 node.js 从标准输出实时读取
【发布时间】:2016-03-16 19:47:37
【问题描述】:

我有一个问题,我需要从控制台输出实时读取。我有一个需要执行的文件,尝试执行类似test.exe > text.txt 的操作,但是当我在 exe 文件运行时尝试读取时,我看不到任何内容,直到 exe 完成并同时写入所有行。我需要使用 node.js 来做到这一点

【问题讨论】:

  • test.exe 生成输出,您需要对该输出做些什么吗?还是 test.exe 你的程序。
  • test.exe 是我启动并生成输出的程序,我尝试将其重定向到文件,但在 test.exe 完成之前我无法从文件中读取任何内容。它类似于execFile('test.exe > test.txt',function(err, stdout, stderr) { console.log(stdout); }).on('data', function (stdout){ sendResponse(); console.log(stdout.toString() + "stdout"); }); 我需要在运行时从 test.txt 中读取,并将其作为对来自客户端的发布请求的响应发送。我需要为那个 test.exe 程序做一些类似进度条的事情。

标签: node.js file console stdout


【解决方案1】:

您应该能够使用child_process.spawn() 启动进程并从其stdout/stderr 流中读取:

var spawn = require('child_process').spawn;
var proc = spawn('test.exe');
proc.stdout.on('data', function(data) {
  process.stdout.write(data);
});
proc.stderr.on('data', function(data) {
  process.stderr.write(data);
});
proc.on('close', function(code, signal) {
  console.log('test.exe closed');
});

【讨论】:

    【解决方案2】:

    test.exe 可能会缓冲它的输出。

    您可以尝试使用 spawn 或 pseudo tty 运行它

    const spawn = require('child_process').spawn;
    const type = spawn('type.exe');
    
    type.stdout.on('data', (data) => {
      console.log(`stdout: ${data}`);
    });
    
    type.stderr.on('data', (data) => {
      console.log(`stderr: ${data}`);
    });
    
    type.on('close', (code) => {
      console.log(`child process exited with code ${code}`);
    });
    

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多