Billions McMillions
Billions McMillions

Reputation: 395

Storing spawn stdout result as string variable in Node.js

I'm trying to return the output of this function into a variable to be used in another function, but the variable returns as undefined. What am I doing wrong?

function run(cmd){
    var spawn = require('child_process').spawn;
    var command = spawn(cmd);
    var result = '';
      command.stdout.on('data', function(data) {
         result += data.toString();
      });
      command.on('close', function(code) {
         return result;
      });
}
var message = run("ls");
sendMessage(user, message);

Upvotes: 2

Views: 3890

Answers (1)

robertklep
robertklep

Reputation: 203359

Your run function is asynchronous (because spawn is). The simplest method of passing its result would be to provide a callback function which is called when the results are in:

function run(cmd, cb) {
  var spawn = require('child_process').spawn;
  var command = spawn(cmd);
  var result = '';
  command.stdout.on('data', function(data) {
    result += data.toString();
  });
  command.on('close', function(code) {
    cb(result);
  });
}
run("ls", function(message) {
  sendMessage(user, message);
});

Upvotes: 4

Related Questions