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.
-
1Look up how to download files (any files, not just XML). There isn't a library specifically for downloading XML because there's nothing special about XML files in that regard.JJJ– JJJ2013-10-05 07:30:33 +00:00Commented Oct 5, 2013 at 7:30
-
Ok. So I should download it, the parse it? Because with rss and feedparser i could just parse it by inputting an urlmeadowstream– meadowstream2013-10-05 07:32:12 +00:00Commented Oct 5, 2013 at 7:32
Add a comment
|
3 Answers
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
});
2 Comments
meadowstream
Thank you! It all starts to make sense now. =D
user3685427
Don't forget that you need to include this line first: var http = require('http');
Using node-fetch
Here an example using node-fetch retrieving xml.
Install a lower version of node-fetch to use require or else use regular ESM import.
npm install node-fetch@^2.6.6
const fetch = require('node-fetch');
const xml_to_js = require('xml-js');//npm i xml-js
var query = "https://api.dreamstime.com/api.xml?username="+usernamer+"&password="+api_key+"&type=get&request=search&srh_field="+term;
fetch(query, {
method: 'GET',
headers: {
'Content-Type': 'text/xml',
'User-Agent': '*'
},
}).then(function(response){ return response.text(); })
.then(function(xml) {
//convert to workable json
var json_result = xml_to_js.xml2json(xml, {compact: true, spaces: 4});
console.log(json_result);//json
})
.catch((error) => {
console.error('Error:', error);
});