How do you fetch an xml from online with node.js and parse it into a javascript object? I’ve been searching the npm register but only found how to parse the xml-string, not how to fetch it.
Advertisement
Answer
To fetch an online resource, you can use http.get(). The data can be loaded into memory, or directly sent to a XML parser since some support the feature of parsing streams.
var req = http.get(url, function(res) {
// save the data
var xml = '';
res.on('data', function(chunk) {
xml += chunk;
});
res.on('end', function() {
// parse xml
});
// or you can pipe the data to a parser
res.pipe(dest);
});
req.on('error', function(err) {
// debug error
});