From 30129852ab83aa9560a0838470a91b6e9d2692c1 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sat, 27 Aug 2016 06:41:59 +0200 Subject: [PATCH] remove socket `error` handler after request is done `npm-registry-client` uses `request`, which in turn uses an HTTP agent for reusing sockets, so the `error` handlers registered on it in `npm-registry-client` just piled up and kept being attached over the entire lifetime of the socket. This patch seeks to fix this by removing the listener from the socket once the callback is invoked, as keeping it around after that would just be a memory leak. --- lib/request.js | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/lib/request.js b/lib/request.js index 567fc8d..976774d 100644 --- a/lib/request.js +++ b/lib/request.js @@ -92,7 +92,16 @@ function regRequest (uri, params, cb_) { } function makeRequest (uri, params, cb_) { - var cb = once(cb_) + var socket + var cb = once(function (er, parsed, resp, data) { + if (socket) { + // The socket might be returned to a pool for re-use, so don’t keep + // the 'error' from here attached. + socket.removeListener('error', cb) + } + + return cb_(er, parsed, resp, data) + }) var parsed = url.parse(uri) var headers = {} @@ -150,7 +159,8 @@ function makeRequest (uri, params, cb_) { req.on('error', cb) req.on('socket', function (s) { - s.on('error', cb) + socket = s + socket.on('error', cb) }) if (params.body && (params.body instanceof Stream)) {