Reputation: 902
How do I write a Transform Stream that turns the XML text in a node Req object into JSON so I can pipe it directly to a Node response?
I am building a sort of proxy or wrapper around an XML based web service, to turn the XML into a RESTFul JSON api. The idea is this:
User makes a request to the proxy, the proxy sends a request to the XML service, and gets back a Node Response Stream, which is transformed (by magic stream thing I can't do yet) into JSON and then piped directly back to the response and sent back to the original user.
I can get this to work quite well with Express, or a simple Node Proxy app, with the exception of the XML to JSON part. I understand that I need to build a Transform stream as defined by substack in his stream-handbook and I think I can make use of streamify, but I am uncertain how to proceed.
here is the route I have set up for my express 4 app. I am using superagent to make the second request. This works, but doesn't transform.
'use strict';
var express = require('express'),
router = express.Router(),
request = require('superagent'),
router.get('/', function(req, res) {
request
.post('http://server.com/some.xml')
// .pipe(converter(res))
.pipe(res)
});
module.exports = router;
Upvotes: 1
Views: 704
Reputation: 106746
Your best bet is to create a Transform stream that internally uses a module like sax to parse the XML. From there it's up to you how you want to format/output the JSON (especially how you want to deal with XML node attributes and the like).
Also, I'm not familiar with superagent
, but you will need to handle the case when the xml request fails so you know to res.send(500);
instead.
Upvotes: 1