繁体   English   中英

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

[英]exec error: Error: stdout maxBuffer exceeded if using child_process on Node js

我想使用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

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

您不能使用exec因为top永远不会结束。 使用spawn ,而不是和开关topbatch 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}`);
});

exec()将缓冲stdout

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

来自文档。

如果在没有其他参数的情况下启动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}`);
});

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM