Вопрос

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!

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top