Skip to content

Commit 9f92332

Browse files
committed
[refactor] Improved event handler cleanup
1 parent 9e630da commit 9f92332

File tree

1 file changed

+40
-18
lines changed

1 file changed

+40
-18
lines changed

lib/node-http-proxy/http-proxy.js

+40-18
Original file line numberDiff line numberDiff line change
@@ -236,24 +236,46 @@ HttpProxy.prototype.proxyRequest = function (req, res, buffer) {
236236

237237
res.on('drain', ondrain);
238238

239-
//
240-
// When the `reverseProxy` `response` ends, end the
241-
// corresponding outgoing `res` unless we have entered
242-
// an error state. In which case, assume `res.end()` has
243-
// already been called and the 'error' event listener
244-
// removed.
245-
//
246-
response.on('end', function () {
247-
if (!errState) {
248-
reverseProxy.removeListener('error', proxyError);
249-
250-
try { res.end() }
251-
catch (ex) { console.error("res.end error: %s", ex.message) }
252-
253-
// Emit the `end` event now that we have completed proxying
254-
self.emit('end', req, res);
255-
}
256-
});
239+
function onend() {
240+
cleanup();
241+
res.end();
242+
}
243+
244+
function onclose() {
245+
cleanup();
246+
res.destroy();
247+
}
248+
249+
response.on('close', onclose);
250+
response.on('end', onend);
251+
252+
response.on('error', proxyError);
253+
res.on('error', proxyError);
254+
255+
256+
function cleanup() {
257+
response.removeListener('data', ondata);
258+
res.removeListener('drain', ondrain);
259+
260+
response.removeListener('end', onend);
261+
response.removeListener('close', onclose);
262+
263+
response.removeListener('error', proxyError);
264+
res.removeListener('error', proxyError);
265+
266+
response.removeListener('end', cleanup);
267+
response.removeListener('close', cleanup);
268+
269+
res.removeListener('end', cleanup);
270+
res.removeListener('close', cleanup);
271+
}
272+
273+
response.on('end', cleanup);
274+
response.on('close', cleanup);
275+
276+
res.on('end', cleanup);
277+
res.on('close', cleanup);
278+
257279
});
258280

259281
//

0 commit comments

Comments
 (0)