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

心已入冬 提交于 2019-12-06 15:00:59

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.

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