Skip to content
This repository was archived by the owner on Aug 11, 2021. It is now read-only.

Commit 0ff3352

Browse files
addaleaxothiym23
authored andcommitted
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.
1 parent 04f418a commit 0ff3352

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

lib/request.js

+16-2
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,16 @@ function regRequest (uri, params, cb_) {
9292
}
9393

9494
function makeRequest (uri, params, cb_) {
95-
var cb = once(cb_)
95+
var socket
96+
var cb = once(function (er, parsed, raw, response) {
97+
if (socket) {
98+
// The socket might be returned to a pool for re-use, so don’t keep
99+
// the 'error' listener from here attached.
100+
socket.removeListener('error', cb)
101+
}
102+
103+
return cb_(er, parsed, raw, response)
104+
})
96105

97106
var parsed = url.parse(uri)
98107
var headers = {}
@@ -149,8 +158,13 @@ function makeRequest (uri, params, cb_) {
149158
var req = request(opts, params.streaming ? undefined : decodeResponseBody(done))
150159

151160
req.on('error', cb)
161+
162+
// This should not be necessary, as the HTTP implementation in Node
163+
// passes errors occurring on the socket to the request itself. Being overly
164+
// cautious comes at a low cost, though.
152165
req.on('socket', function (s) {
153-
s.on('error', cb)
166+
socket = s
167+
socket.on('error', cb)
154168
})
155169

156170
if (params.streaming) {

test/lib/common.js

+8
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,14 @@ if (!global.setImmediate || !require('timers').setImmediate) {
1010
}
1111
}
1212

13+
// See https://github.com/npm/npm-registry-client/pull/142 for background.
14+
// Note: `process.on('warning')` only works with Node >= 6.
15+
process.on('warning', function (warning) {
16+
if (/Possible EventEmitter memory leak detected/.test(warning.message)) {
17+
throw new Error('There should not be any EventEmitter memory leaks')
18+
}
19+
})
20+
1321
module.exports = {
1422
port: server.port,
1523
registry: REGISTRY,

0 commit comments

Comments
 (0)