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)