Search code examples
node.jsxmlxml2js

Passing XML File To xml2js With Node.js


Background

I have taken some sample data from a large XML response I will be working with in my app. I decided to save the xml to a response.xml file in my app so I can parse the data without making a bunch of unnecessary request to the api.

I am going to be using xml2js to convert the xml response to a JS Object.

Problem

I have been able to open the file and console.log() it.

I have been able to run xml2js by passing a small xml string to it which I also console.log() it.

But I have only been able to console.log() the file after xml2js creates the object. No matter what I try I continue to get null when using return or passing trying to pass the data outside of the initial creation of the object.

Example

This prints xml tree to the console,

var fs = require('fs');
var openFile = fs.readFile('./response.xml', 'utf8', function (err,data) {
    if (err) {
        return console.log(err);
    }
    console.log(data);
});

function requestCreditReport() {
    return openFile;
}

requestCreditReport();

This prints a small xml string to console statically added in with xml2js,

var parseString = require('xml2js').parseString;

var xml = "<root>Hello xml2js!</root>";

parseString(xml, function (err, result) {
    console.dir(result);
});

Question

How do I use the object once it is created outside of the method below. Initially when it is created I can output it to the console but cannot seem to access it outside of that console.log(). in the example below I am trying return result. This leaves the value null when I try to pass the object returned by the function to a variable like this,

var response = requestReport();

Recent try,

var fs = require('fs');
var parseString = require('xml2js').parseString;

function requestReport() {
    fs.readFile('./response.xml', 'utf8', function (err,data) {
        if (err) {
            return console.log(err);
        }
        return parseString(data, function (err, result) {
            return result;
        });
    });
}

var response = requestReport();

console.log(response);

This returns null. But if I console.log(result) instead or using return then trying outside of the function it returns this,

{ RESPONSE_DATA:
   { '$': { MYAPI: '0.0.0' },
     DETAILS: [ [Object] ],
     DETAILS_ACCOUNT: [ [Object] ],
     RESPONSE: [ [Object] ] } }

Solution

  • requestReport is async. It doesn't return anything so response is undefined.

    You have to use a callback.

    var fs = require('fs');
    var parseString = require('xml2js').parseString;
    
    function requestReport(callback) {
      fs.readFile('./response.xml', 'utf8', function(err, data) {
        if (err) return callback(err);
        parseString(data, callback);
      });
    }
    
    requestReport(function(err, result) {
      if (err) return console.error(err);
      console.log(result);
    });