如何在node.js上运行带有子进程的top命令,而不会超出' stdout maxBuffer'从终端

时间:2017-07-12 21:41:02

标签: node.js linux

我正在尝试创建一个从虚拟机获取指标的REST API,但我似乎无法运行我的子进程,而不会超出'标准超出maxBuffer'。这是我的代码

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}`);
});

1 个答案:

答案 0 :(得分:3)

top(使用它的默认参数)将继续写入stdout - 它不只是转储一些信息并退出。

如果您想使用top,请查看手册页。特别是-b选项:

  -b  :Batch-mode operation
        Starts top in 'Batch' mode, which could be useful for sending output from top to other programs or to a file.  In this mode, top will not accept input and runs until the  iterations  limit  you've  set
        with the '-n' command-line option or until killed.

请尝试top -b -n 1top获取单个“批量”信息,然后解析该信息。