Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js write after end error zlib

I have the following code where I'm piping the request of a URL that's gzipped. This works just fine, however if I try to execute the code a few times, I get the below error. Any suggestions how to work around this?

Thank you!

http.get(url, function(req) {

   req.pipe(gunzip);

   gunzip.on('data', function (data) {
     decoder.decode(data);
   });

   gunzip.on('end', function() {
     decoder.result();
   });

});

Error:

  stack: 
   [ 'Error: write after end',
     '    at writeAfterEnd (_stream_writable.js:125:12)',
     '    at Gunzip.Writable.write (_stream_writable.js:170:5)',
     '    at write (_stream_readable.js:547:24)',
     '    at flow (_stream_readable.js:556:7)',
     '    at _stream_readable.js:524:7',
     '    at process._tickCallback (node.js:415:13)' ] }
like image 798
dzm Avatar asked Oct 25 '13 21:10

dzm


People also ask

Why zlib is used in Node JS?

The node:zlib module can be used to implement support for the gzip , deflate and br content-encoding mechanisms defined by HTTP. The HTTP Accept-Encoding header is used within an HTTP request to identify the compression encodings accepted by the client.


1 Answers

Once a writable stream is closed, it cannot accept anymore data (see the documentation): this is why on the first execution your code will work, and on the second you'll have the write after end error.

Just create a new gunzip stream for each request:

http.get(url, function(req) {
   var gunzip = zlib.createGzip();
   req.pipe(gunzip);

   gunzip.on('data', function (data) {
     decoder.decode(data);
   });

   gunzip.on('end', function() {
     decoder.result();
   });

});
like image 106
Paul Mougel Avatar answered Oct 07 '22 11:10

Paul Mougel