简体   繁体   中英

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 = 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; 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. 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. 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);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM