10

我有以下代码,我在其中通过管道传输 gzip 压缩的 URL 的请求。这工作得很好,但是如果我尝试执行几次代码,我会收到以下错误。有什么建议可以解决这个问题吗?

谢谢!

http.get(url, function(req) {

   req.pipe(gunzip);

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

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

});

错误:

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

1 回答 1

21

一旦可写流关闭,它就不能再接受数据(请参阅文档):这就是为什么在第一次执行时您的代码将起作用,而在第二次执行时您将遇到write after end错误。

只需为每个请求创建一个新的 gunzip 流:

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

});
于 2013-12-17T10:05:39.290 回答