Node.js: Object value as stdout of child_process.exec

人盡茶涼 提交于 2019-12-22 16:45:01

问题


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:


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.



来源:https://stackoverflow.com/questions/10270857/node-js-object-value-as-stdout-of-child-process-exec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!