简体   繁体   中英

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

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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM