dzm
dzm

Reputation: 23544

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)' ] }

Upvotes: 10

Views: 8809

Answers (1)

Paul Mougel
Paul Mougel

Reputation: 17038

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();
   });

});

Upvotes: 21

Related Questions