Skip to content

Commit

Permalink
[fix] Handle cases where the 'error' event is emitted multiple times
Browse files Browse the repository at this point in the history
The `'error'` event can be emitted multiple times by the
`http.ClientRequest` object in Node.js < 13. Handle the case properly.

Fixes websockets#1819
  • Loading branch information
lpinca committed Dec 4, 2020
1 parent 3d5066a commit 334a278
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -572,7 +572,7 @@ function initAsClient(websocket, address, protocols, options) {
}

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

req = websocket._req = null;
websocket._readyState = WebSocket.CLOSING;
Expand Down
33 changes: 33 additions & 0 deletions test/websocket.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2242,6 +2242,39 @@ describe('WebSocket', () => {

const ws = new WebSocket('wss://127.0.0.1', { servername: '' });
});

it("works around a double 'error' event bug in Node.js", (done) => {
//
// The `minVersion` and `maxVersion` options are not supported in
// Node.js < 10.16.0.
//
if (process.versions.modules < 64) return this.skip();

//
// The `'error'` event can be emitted multiple times by the
// `http.ClientRequest` object in Node.js < 13. This test reproduces the
// issue in Node.js 12.
//
const server = https.createServer({
cert: fs.readFileSync('test/fixtures/certificate.pem'),
key: fs.readFileSync('test/fixtures/key.pem'),
minVersion: 'TLSv1.2'
});
const wss = new WebSocket.Server({ server });

server.listen(0, () => {
const ws = new WebSocket(`wss://localhost:${server.address().port}`, {
maxVersion: 'TLSv1.1',
rejectUnauthorized: false
});

ws.on('error', (err) => {
assert.ok(err instanceof Error);
server.close(done);
wss.close();
});
});
});
});

describe('Request headers', () => {
Expand Down

0 comments on commit 334a278

Please sign in to comment.