How to convert (simple) streaming XML to Node.js?

I have proxied an S3 call through my Node.js server and want to configure only a couple of returned XML values โ€‹โ€‹before they are maximized. With the exception of these settings, I would like to save the rest of each answer, for example. response headers.

I can, of course, first collect the whole answer, parse the XML, convert it and return it, but for large answers that will be slow and memory intensive. Is there a way that I can achieve basically stream.pipe() , but maybe with a conversion function?

I looked at sax-js , which may work, but does not have the ability to convert. Should I resort to listening to low-level parsing events and generating and outputting the resulting XML file?

I also looked at libxmljs , which has a โ€œparserโ€ and a higher level DOM API, but it looks like I have to listen to parsing events myself again at a low level, and I'm not sure if I can pass the resulting XML result via least of its creation.

Is there an easier way than either of these two approaches? Thanks!

PS XML settings are simple: just remove the substring from some text elements.

+4
source share
1 answer

In this case, you can put all the pieces together, for example:

 var data='', tstream = new stream.Transform(); tstream._transform = function (chunk, encoding, done) { data += chunk.toString(); done(); }; 

And do what you need in the last call to the _flush function:

 tstream._flush = function(done){ data += 'hola muheres'; this.push(data); done(); }; 

so it may all look like this:

 req.pipe(anotherstream).pipe(tstream).pipe(response); 
+3
source

Source: https://habr.com/ru/post/1438556/


All Articles