Xml2js: include parser in function

I got this code on my NodeJS server:

function GetXML() {
    fs.readFile('../slideshow.xml.old', function(err, data) {
        parser.parseString(data, function (err, result) {
            var json = JSON.stringify(result);
            console.log(json);
            return json;
        });
    });
}

      

console.log()

works well, but it doesn't:

.get('/', function(req, res) {
    res.end(GetXML());
};

      

It returns undefined

, which is pretty logical because the functions are nested (I guess?). But I don't know how to get GetXML () to return a value.

+3


source to share


2 answers


Returns undefined

because you are trying to execute an asynchronous task synchronously. You have to pass a callback to your function GetXML()

, for example:

function GetXML(cb) {
  fs.readFile('../slideshow.xml.old', function(err, data) {
    parser.parseString(data, function (err, result) {
      var json = JSON.stringify(result);
      cb(json);
    });
  });
}

      

and call it correctly in your function .get

:



.get('/', function(req, res) {
  GetXML(function (json) {
    res.end(json);
  });
};

      

You should take a look at this article which explains how it callbacks

works in node.js.

+1


source


GetXML returns no value. It can be changed to:



function GetXML() {
    return fs.readFile('../slideshow.xml.old', function(err, data) {
        parser.parseString(data, function (err, result) {
            var json = JSON.stringify(result);
            console.log(json);
            return json;
        });
    });
}

      

0


source







All Articles