Node.js:对象值作为child_process.exec的stdout [英] Node.js: Object value as stdout of child_process.exec

查看:548
本文介绍了Node.js:对象值作为child_process.exec的stdout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node的新手,对它的一些非阻塞性元素s之以鼻。我正在尝试创建一个对象,并将其元素之一作为返回child_process.exec的stdout的函数,如下所示:

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);

我认为 myObj.list 正在返回结果设置为 stdout 之前,但我不知道如何使其等待或执行回调为了它。谢谢您的帮助!

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);
});

在实际代码中,您可能希望回调函数将错误作为第一个参数,不必这么做,但这是在Node.JS中完成的正常方法。

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.

这篇关于Node.js:对象值作为child_process.exec的stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆