user3698126
user3698126

Reputation: 89

(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

Upvotes: 1

Views: 3915

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146064

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

Upvotes: 1

Related Questions