0

I am trying to export a function that grabs XML from an endpoint, parses it and turns it into a json object. I am having trouble getting the json object to return. I am familiar that the parse is running async and requires a callback to return the value. I just cannot seem to figure out how to write it out properly.

Another note... What would be the "best" way to export this function? I am trying to make a utility where I send in any endpoint that produces an xml and it spits out a json. Do I need to wrap my requires in the exported function? Or should I keep it exclusively for the methods below?

getXmlToObj.js

    module.exports = function getXML(xmlUrl,callback){
// Requires --------------------------------------------------------------------
  var https = require('https'),
    xml2js = require('xml2js'),
    parser = new xml2js.Parser();
// End Requires ----------------------------------------------------------------

  // We append the XML as a string to data
  var data = "";

  //error check on xml2js parse
  parser.on('error', function(err) { console.log('Parser error', err); });


    https.get(xmlUrl, function(res) {
        if (res.statusCode >= 200 && res.statusCode < 400) {
          res.on('data', function(data_) {
             data += data_.toString();
          });
          res.on('end', function() {
            parser.parseString(data, function(err, result) {
              //console.log('FINISHED', err, result);
              //var json = JSON.stringify(result)
              //console.log(json)
              return callback(result);
            });
          });
        }
    });
};

Avi-WX-API.js

var getXml = require('./getXmlToObj');


url = 'https://aviationweather.gov/adds/dataserver_current/httpparam?datasource=metars&requestType=retrieve&format=xml&mostRecentForEachStation=constraint&hoursBeforeNow=1.25&stationString=KFRG'

var x = getXml(url,function(json){
  return json;
})
console.log(x)
  • The data is only available inside the callback, not outside of it. `getXML` returns `undefined`. You can *pass* `json` *to* other functions though. – Felix Kling Feb 12 '17 at 17:24
  • 1
    You have it; the value you want is in the variable `json`. It's only accessible within that callback function where `json` is defined as an argument. Also, there's no need to `return` in your `getXml` or capture the return value in `x`; all the value-passing is done inside callbacks. – apsillers Feb 12 '17 at 17:25
  • Thanks for the feedback guys. Is there a way I can access the json in the global scope? –  Feb 12 '17 at 17:41
  • @HyosunIsaksenTakaaki You can do something like `var globalJson` and then `getXml(url,function(json){ globalJson = json; })`, *however* the real issue is timing. Whenever the callback runs, `globalJson` will be populated, but you have no way to know when that will be (except by having your code that depends on `json` wait until the callback runs; i.e., put your code inside the callback). This is sometimes (rarely) useful if, for example, you have another event that could happen at any time (like a user clicking a button) that can use `globalJson` or tolerate a possibly still-empty value. – apsillers Feb 12 '17 at 17:44
  • Awesome. Thanks for that explanation. –  Feb 12 '17 at 21:04

0 Answers0