结束后,Node.js写入错误zlib

我有下面的代码,我正在pipe道的URL请求gzipped。 这工作得很好,但是如果我尝试执行代码几次,我得到下面的错误。 任何build议如何解决这个问题?

谢谢!

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

一旦一个可写入的stream被closures,它就不能再接受数据了( 参见文档 ):这就是为什么在第一次执行代码的时候你的代码将会工作,而第二次你将会有write after end错误。

只需为每个请求创build一个新的gunzipstream:

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