我有以下代码,我正在管道请求一个 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)' ] }
一旦可写流关闭,它就不能再接受数据(请参阅文档): 这就是为什么在第一次执行时,您的代码将起作用,而在第二次执行时,您将遇到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();
});
});