node.js - 执行错误 : Error: stdout maxBuffer exceeded if using child_process on Node js

标签 node.js linux

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

代码:

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() 将缓冲 stdout

Spawns a shell then executes the command within that shell, buffering any generated output.

( From the docs. )

top 在没有其他参数的情况下启动时,它会尝试重绘部分终端。我不知道你能来这么远。在我的系统上你的代码失败了:

top: failed tty get

您需要告诉 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 监听器,您可以及时观察数据。

关于node.js - 执行错误 : Error: stdout maxBuffer exceeded if using child_process on Node js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51967909/

相关文章:

c - Popen 导致程序卡住

node.js - v8中如何防止对象被自动回收

linux - Linux 应用程序如何确定标准输出是终端文件还是普通文件

node.js - Material-UI 迁移助手 : codemod-script?

node.js - Mongoose 首先按一个属性排序和限制,然后按另一个属性排序

linux - 无法通过squid3访问https网站

linux - 如何使用 bash 从文本文件中删除前两行和后四行?

linux - 如何安装需要dailyjobs的cronie

javascript - 导出 Node.js 模块

node.js - Nodemailer 是免费的 api/库吗?