[英]Assigning value to a global variable inside a callback function and returning it [Node.js]
I have an xml file with leagues there xml tree is so nexted with so many nodes but i want to return only the id and the name of each leage, i am using the xml-object-stream
node module that can be found at https://github.com/idottv/xml-object-stream . 我有一个xml文件与联盟那里xml树是如此多的节点,但我想只返回每个leage的id和名称,我使用可以在https找到的xml-object-stream
节点模块: //github.com/idottv/xml-object-stream 。
xml = require('xml-object-stream'),
fs = require('fs');
function buildLeagues(cb){
var leaguesData = [];
var data = fs.createReadStream("./tmp/leagues.xml");
var parser = xml.parse(data);
var parser.each('league', function(league){
var leagues = {};
leagues.id = league.$.id ;
leagues.name = league.$text;
leaguesData.push(leagues);
});
cb(JSON.stringify(leaguesData));
} }
The problem i have with this function is with javascript scopes; 这个函数的问题是javascript范围; the leaguesData
variable is always returning []
because of the new scope in the callback function, i even tried declaring it in a global scope but the same issue, can anyone suggest a better approach to build my json
data from a bulk xml
file. leaguesData
变量总是返回[]
因为回调函数中的新范围,我甚至尝试在全局范围内声明它但同样的问题,任何人都可以提出一个更好的方法来从批量xml
文件构建我的json
数据。 Thank you 谢谢
From the docs: 来自文档:
The parser emits some streaming events 解析器发出一些流事件
parser.on 'end', -> parser.on 'error', (err) -> parser.on 'close', ->
That means you should trigger your callback when the event stream is done and your leaguesData
array contains all results. 这意味着您应该在事件流完成时触发回调,并且您的leaguesData
数组包含所有结果。 So try 所以试试吧
var xml = require('xml-object-stream'),
var fs = require('fs');
function buildLeagues(cb){
var leaguesData = [];
var data = fs.createReadStream("./tmp/leagues.xml");
var parser = xml.parse(data);
parser.each('league', function(league){
leaguesData.push({
id: league.$.id,
name: league.$text
});
});
parser.on("end", function() {
cb(null, JSON.stringify(leaguesData)); // are you sure you need to stringify?
});
parser.on("err", function(err) {
cb(err, leaguesData);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.