节点。对象值为child_process.exec中的stdout

时间:2022-12-02 00:01:35

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:

我是Node的新成员,在它的一些非阻塞元素上出错了。我试着创建一个对象,其中的一个元素是一个函数,它返回一个child_process的stdout。执行,就像这样:

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!

我图myObj。list在将其设置为stdout之前返回结果,但是我不知道如何让它等待或做回调。谢谢你的帮助!

1 个解决方案

#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.

在实际代码中,您可能希望将回调作为它的第一个参数作为第一个参数,您不必这样做,但它是在Node.JS中所做的正常方式。

#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.

在实际代码中,您可能希望将回调作为它的第一个参数作为第一个参数,您不必这样做,但它是在Node.JS中所做的正常方式。