From cd97423db96132616766873bd25964e96f0bf61f Mon Sep 17 00:00:00 2001 From: Rob Wu Date: Thu, 29 Aug 2013 15:17:19 +0200 Subject: [PATCH] Fix memory leak --- lib/cors-anywhere.js | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/cors-anywhere.js b/lib/cors-anywhere.js index 7026469..a350ba7 100644 --- a/lib/cors-anywhere.js +++ b/lib/cors-anywhere.js @@ -142,11 +142,27 @@ function onProxyResponse(req, res, response) { req.method = 'GET'; requestState.location = parseURL(locationHeader); + + // ### Dispose the current proxied request + // Verified assumption: When proxy.proxyRequest is called for the first time, + // there are no event listeners on the "req" object. + + // First remove the "end" event, to avoid the req.end() call by node-http-proxy/http-proxy + // https://github.com/nodejitsu/node-http-proxy/blob/ebbba73e/lib/node-http-proxy/http-proxy.js#L310-319 + response.removeAllListeners('end'); + // Trigger disposal of the reverseProxy + // https://github.com/nodejitsu/node-http-proxy/blob/ebbba73e/lib/node-http-proxy/http-proxy.js#L375-L378 + req.emit('aborted'); + // Remove all listeners (=events reset to initial state) + req.removeAllListeners(); + + // Initiate a new proxy request. proxyRequest(req, res, proxy); // Trigger reverseProxy.end() to initiate the proxy + // The event listener is added at the end of HttpProxy.prototype.proxyRequest, synchronously. + // https://github.com/nodejitsu/node-http-proxy/blob/ebbba73e/lib/node-http-proxy/http-proxy.js#L407-L415 req.emit('end'); - response.end(); // The proxyResponse event is wrapped in a try-catch, throwing an error // prevents the response from being passed to the client. throw new Error('Prevent current response from being passed through.');