如何使用node.js在node-zookeeper客户端中同时使用getChildren和getData方法
How to use getChildren and getData method together in node-zookeeper-client using Node.js?
我是Node.js的新手。我正在尝试从npm(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
如果你看到数据,它会被打印为未定义。我希望每个都有正确的数据要打印而不是未定义的单个子节点。
有人能帮忙吗?谢谢
PS:数据在client.getData()的函数中打印,但不会分配给变量str.
getData
是一个异步函数,您将无法将值返回给调用者。它将始终是未定义的,因为稍后会在不同的堆栈中调用回调。
要打印出数据,需要将console.log
语句放入getData回调函数中。例如
client.getData(newPath, function(error,data){
if (error) {
console.log(error.stack);
return;
}
console.log('Node: %s has DATA: %s', newPath, data ? data.toString() : '');
});
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- 有没有任何方法可以将控制器从文件加载到ui路由器$stateProvider中
- 数组在递归方法中设置为null
- 打破承诺链的好方法是什么
- 在使用Polymer'加载所有json文件后执行方法;s的核心ajax
- 使用“;这个“;JavaScript原型方法中的关键字
- 序列化数据属性中对象的最可靠方法
- 使用Objective-C的JavaScript注入方法
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象
- 有没有一种方法可以防止img get请求使用css或js发生
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- toBoolean方法类似于toString
- 如何在单击复选框后调用控制器方法
- 是否有任何方法可以使用jQuery替换在数组中定义值的文本
- 递归使用 eval() 是检查程序执行的好方法吗?
- 如何在webView,Android中从@JavascriptInterface方法调用Javascript
- toLocaleDateString和toLocaleString方法不尊重机器时区
- 有条件更新d3.js力图中节点的最佳方法
- TypeError:在不兼容的接收器nodejs上调用了方法Uint8Array.length
- 如何使用node.js在node-zookeeper客户端中同时使用getChildren和getData方法