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;
});
});
}
The console.log()
is working well but this is not:
.get('/', function(req, res) {
res.end(GetXML());
};
It returns undefined
which is quite logic because functions are nested (I think ?). But I don't know how to make GetXML() returning a value.
It's returning undefined
because you're trying to execute synchronously an asynchronous task. You have to pass a callback to your GetXML()
function, like:
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 properly in your .get
function:
.get('/', function(req, res) {
GetXML(function (json) {
res.end(json);
});
};
You should take a look at this article that explains how callbacks
work in node.js.
"GetXML" is not returning a value. It can be change 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;
});
});
}