exec错误:错误:如果在节点js上使用child_process,则超出stdout maxBuffer

时间:2018-08-22 13:22:47

标签: node.js linux

我想使用topchild_process.exec从Linux上的监视进程和系统资源使用情况连续获取数据。

代码:

const { exec } = require('child_process');
exec('top', (error, stdout, stderr) => {
    if (error) {
        console.error(`exec error: ${error}`);
        return;
    }
    console.log('stdout', stdout);
    console.log('stderr', stderr);
});

如果我在上面运行代码,则会收到错误exec error: Error: stdout maxBuffer exceeded

我正在使用Node.js版本v8.9.4

是否可以使用topchild_process.exec命令连续获取数据?

2 个答案:

答案 0 :(得分:1)

You can't use exec because top will never end. Use spawn instead and switch top to batch mode

const { spawn } = require('child_process');
const top = spawn('top', ['-b']);

top.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

top.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

top.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

答案 1 :(得分:1)

exec()将缓冲stdout

  

生成一个shell,然后在该shell中执行命令,缓冲所有生成的输出。

From the docs.

在启动top时不带其他参数的情况下,它将尝试重绘终端的部分内容。我不知道你到现在为止。在我的系统上,您的代码因以下原因而失败:

  

顶部:tty获取失败

您需要告诉top以批处理模式运行,以便在每次更新时完全转储其当前状态。

exec('/usr/bin/top -b', ...);

尽管top将无限期地转储状态,但缓冲区最终仍将溢出。您可以使用-n #开关限制更新次数,也可以使用spawn()

const { spawn } = require("child_process");

// Note: -b for batch mode and -n # for number of updates
let child = spawn("/usr/bin/top", ["-b", "-n", "2"]);

// Listen for outputs
child.stdout.on("data", (data) => {
    console.log(`${data}`);
});

在子进程的data流上使用stdout侦听器,您可以及时观察数据。