2

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);
2
  • What is your problem? Commented Mar 20, 2013 at 5:49
  • Sorry updated my question. My problem is that the variable keeps returning as undefined. Commented Mar 20, 2013 at 5:52

1 Answer 1

4

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.