使用node.js实时读取stdout

3

我有一个问题,需要实时从控制台输出中读取内容。我有一个需要执行的文件,试着这样做test.exe > text.txt但是当我尝试在exe文件运行时读取数据,我看不到任何东西直到exe完成并一次性写入所有行。我需要使用node.js实现。


test.exe生成输出,你需要对该输出做些什么?还是test.exe是你的程序? - skarface
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中读取并将其作为响应发送到客户端的POST请求。我需要为该test.exe程序做类似进度条的东西。 - Душан Мијаиловић
2个回答

5

您可以使用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');
});

1

test.exe 可能会缓冲其输出。

您可以尝试使用 spawn 运行它,或者使用 伪终端

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接