Skip to content

Commit 38d6ab3

Browse files
committedDec 4, 2020
[fix] Handle cases where the 'error' event is emitted multiple times
The `'error'` event can be emitted multiple times by the `http.ClientRequest` object in Node.js < 13. Handle the case properly. Fixes #1819
1 parent 3d5066a commit 38d6ab3

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed
 

‎lib/websocket.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -572,7 +572,7 @@ function initAsClient(websocket, address, protocols, options) {
572572
}
573573

574574
req.on('error', (err) => {
575-
if (websocket._req.aborted) return;
575+
if (req === null || req.aborted) return;
576576

577577
req = websocket._req = null;
578578
websocket._readyState = WebSocket.CLOSING;

‎test/websocket.test.js

+33
Original file line numberDiff line numberDiff line change
@@ -2242,6 +2242,39 @@ describe('WebSocket', () => {
22422242

22432243
const ws = new WebSocket('wss://127.0.0.1', { servername: '' });
22442244
});
2245+
2246+
it("works around a double 'error' event bug in Node.js", function (done) {
2247+
//
2248+
// The `minVersion` and `maxVersion` options are not supported in
2249+
// Node.js < 10.16.0.
2250+
//
2251+
if (process.versions.modules < 64) return this.skip();
2252+
2253+
//
2254+
// The `'error'` event can be emitted multiple times by the
2255+
// `http.ClientRequest` object in Node.js < 13. This test reproduces the
2256+
// issue in Node.js 12.
2257+
//
2258+
const server = https.createServer({
2259+
cert: fs.readFileSync('test/fixtures/certificate.pem'),
2260+
key: fs.readFileSync('test/fixtures/key.pem'),
2261+
minVersion: 'TLSv1.2'
2262+
});
2263+
const wss = new WebSocket.Server({ server });
2264+
2265+
server.listen(0, () => {
2266+
const ws = new WebSocket(`wss://localhost:${server.address().port}`, {
2267+
maxVersion: 'TLSv1.1',
2268+
rejectUnauthorized: false
2269+
});
2270+
2271+
ws.on('error', (err) => {
2272+
assert.ok(err instanceof Error);
2273+
server.close(done);
2274+
wss.close();
2275+
});
2276+
});
2277+
});
22452278
});
22462279

22472280
describe('Request headers', () => {

0 commit comments

Comments
 (0)
Please sign in to comment.