3

I'm new to Node and stumbling on some of the nonblocking elements of it. I'm trying to create a object and have one of the elements of it being a function that returns the stdout of a child_process.exec, like so:

var exec = require('child_process').exec;
var myObj = {};

myObj.list = function(){
  var result;
  exec("ls -al", function (error, stdout, stderr) {
     result = stdout;
  });
  return result;
}
console.log('Ta da : '+myObj.list);

I figure that myObj.list is returning result before it is set as stdout, but I can't figure out how to make it wait or do a callback for it. Thanks for your help!

1 Answer 1

4

You can't directly return the value as it's not going to be available for a bit. So instead of a return value you need to use a callback which means turning the calling code inside out a bit.

var exec = require('child_process').exec;
var myObj = {};

myObj.list = function(callback){
  var result;
  exec("ls -al", function (error, stdout, stderr) {
     callback(stdout);
  });
  // No return at all!
}
// Instead of taking a return we pass a callback
// which receives the value and carries on our computation.
myObj.list(function (stdout) {
   console.log('Ta da : '+ stdout);
});

In real code you'd probably want to have your callback take an error as its first argument, you don't have to but it's the normal way things are done in Node.JS.

Sign up to request clarification or add additional context in comments.

3 Comments

You're a star, thank you! I especially appreciate the explanation, I have a better understanding now!
@DexCurl how can I execute command "not only reading results", like "exit" for windows .
I need a synchronous call (taht does not invert the caller's logic glow): it's fine (and in fact mandatory) to wait. Are there any options here?

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.