Skip to content

Commit 2a9c833

Browse files
ronagMylesBorins
authored andcommitted
http: fix res emit close before user finish
PR-URL: #20941 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]>
1 parent 0b1ba20 commit 2a9c833

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

lib/_http_server.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -562,7 +562,7 @@ function resOnFinish(req, res, socket, state, server) {
562562

563563
res.detachSocket(socket);
564564
req.emit('close');
565-
res.emit('close');
565+
process.nextTick(emitCloseNT, res);
566566

567567
if (res._last) {
568568
if (typeof socket.destroySoon === 'function') {
@@ -585,6 +585,10 @@ function resOnFinish(req, res, socket, state, server) {
585585
}
586586
}
587587

588+
function emitCloseNT(self) {
589+
self.emit('close');
590+
}
591+
588592
// The following callback is issued after the headers have been read on a
589593
// new message. In this callback we setup the response object and pass it
590594
// to the user.

test/parallel/test-http-req-res-close.js

+12-3
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,21 @@
22

33
const common = require('../common');
44
const http = require('http');
5+
const assert = require('assert');
56

67
const server = http.Server(common.mustCall((req, res) => {
8+
let resClosed = false;
9+
710
res.end();
8-
res.on('finish', common.mustCall());
9-
res.on('close', common.mustCall());
10-
req.on('close', common.mustCall());
11+
res.on('finish', common.mustCall(() => {
12+
assert.strictEqual(resClosed, false);
13+
}));
14+
res.on('close', common.mustCall(() => {
15+
resClosed = true;
16+
}));
17+
req.on('close', common.mustCall(() => {
18+
assert.strictEqual(req._readableState.ended, true);
19+
}));
1120
res.socket.on('close', () => server.close());
1221
}));
1322

0 commit comments

Comments
 (0)