我想在 Linux 上使用 top
和 child_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.exec
从 top
命令连续获取数据?
最佳答案
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/