我是 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。