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



我想使用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()将缓冲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侦听器,您可以及时观察数据。

你不能使用exectop因为永远不会结束。请改用spawn并将top切换到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}`);
});

相关内容

最新更新