如何使用Node.js在node-zookeeper-client中一起使用getChildren和getData方法?

时间:2013-07-29 09:22:29

标签: javascript node.js apache-zookeeper

我是Node.js的新手。我试图从npm使用node-zookeeper-client(Github链接 - https://github.com/alexguan/node-zookeeper-client

我想了解如何在这个库中一起使用getChildren和getData方法。(我知道这些使用了回调)

目标是,遍历给定路径的所有孩子并获取所有孩子的数据并在下一个孩子之前同步打印出来。

var zookeeper = require('node-zookeeper-client');
var client = zookeeper.createClient('localhost:2181');
var path =  "/Services/Apache";
var tmpChildren = [];

function getChildren(client,path){

console.log('path value received is..', path );
client.getChildren(path, function (error, children, stats) {
    if (error) {
        console.log(error.stack);
        return;
    }

    console.log('Children are: %s', children);
    tmpChildren = String(children).split(",");
    var newPath="";

   for(var i=0; i < tmpChildren.length ; i++)
   {
      newPath = path+'/'+tmpChildren[i];
      console.log('children is %s',tmpChildren[i]);
      var str = client.getData(newPath, function(error,data){
             if (error) {
              return error.stack; 
          }
             return data ? data.toString() : undefined;

      });
      console.log('Node: %s has DATA: %s', newPath, str);
  }

}

);

}

client.once('connected', function () 
    {
    console.log('Connected to the server.');
    getChildren(client,path);


});

client.connect();

上面的代码就是我所拥有的。输出如下

Connected to the server.
path value received is.. /Services/Apache
Children are: Instance4,Instance3,Instance2,Instance1
children is Instance4
Node: /Services/Apache/Instance4 has DATA: undefined
children is Instance3
Node: /Services/Apache/Instance3 has DATA: undefined
children is Instance2
Node: /Services/Apache/Instance2 has DATA: undefined
children is Instance1
Node: /Services/Apache/Instance1 has DATA: undefined

如果你看到DATA它被打印为未定义。我希望每个都有正确的数据 要打印的单个子节点而不是未定义。

有人可以帮忙吗?感谢。

PS:数据在 client.getData()的函数内打印,但未分配给变量str。

1 个答案:

答案 0 :(得分:0)

getData是一个异步函数,您将无法将该值返回给调用者。它总是未定义的,因为稍后在不同的堆栈中调用回调。

要打印出数据,需要将console.log语句放在getData回调函数中。 e.g。

  client.getData(newPath, function(error,data){
      if (error) {
          console.log(error.stack); 
          return;
      }

      console.log('Node: %s has DATA: %s', newPath, data ? data.toString() : '');
  });