Search code examples
node.jsspawnnode.js-stream

(Node.js) How to store stdout.pipe into a variable?


I want to get free -m (linux shell command) and store its result into a variable by using source code below:

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

Is there any way to store process.stdout in a variable, please me some suggestions


Solution

  • This is fairly simple with 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