(Node.js)如何将stdout.pipe存储到变量中?

时间:2014-11-08 05:47:53

标签: node.js spawn node.js-stream

我想获得free -m(linux shell命令)并将其结果存储到变量中 使用以下源代码:

 var spawn = require('child_process').spawn,
     command  = spawn('free', ['-m']);
 command.stdout.pipe(process.stdout);

有没有办法将process.stdout存储在变量中,请给我一些建议

1 个答案:

答案 0 :(得分:1)

child_process.exec

相当简单
var child = require("child_process");
var freeOut;
child.exec("free", ["-m"], function (error, stdout, stderr) {
  if (error) {
    console.error(error, stderr);
    return;
  }
  //stdout and stderr are available here
  freeOut = stdout;
  process.stdout.write(stdout);
});
//Note. Do NOT use freeOut here. exec is async. Can only use in the callback