Ben Muircroft Ben Muircroft - 5 months ago 23
Node.js Question

node.js http.get xml is blank

http://www.hmrc.gov.uk/softwaredevelopers/rates/exrates-monthly-0616.xml

I'm trying to get the xml from the above hrmc website url into node.js (I intend to parse it into json later).

As the hrmc states


You should use these exchanges rates if you have to convert any foreign currency to sterling for customs and VAT purposes.


please no answers on alternate places I can find exchange rates

function hrmc(cb){
var m=new Date().getMonth()+1;
if(m<10){m='0'+m;}
var y=((new Date().getFullYear()+'').substr(2));
var req=require('http').get({host:'www.hmrc.gov.uk',path:'/softwaredevelopers/rates/exrates-monthly-'+m+y+'.xml'},function(res){
var xml='';
res.on('error',function(e){console.dir(['res error',e]);});
res.on('data',function(chunk){xml+=chunk;});
res.on('end',function(){
//
console.log(xml);// '' <--empty?
//cb(xml);
});});
req.on('error',function(e){console.dir(['req error',e]);});}


The problem is that I get an empty string and no errors

Answer

It works for me:

var http = require('http');    

http.get('http://www.hmrc.gov.uk/softwaredevelopers/rates/exrates-monthly-0616.xml', (response) => {

    var xml = '';

    response.on('data', function (chunk) {
        xml += chunk;
    });

    response.on('end', function() {
        console.log(xml); //not empty!
    })

}).on('error', (e) => {
    console.log('error: ' + e.message);
});