Skip to content
This repository has been archived by the owner on Aug 31, 2018. It is now read-only.

Commit

Permalink
http: emit close as the last event in the client
Browse files Browse the repository at this point in the history
Emit close event after all other events in the client, e.g.
error will be emitted before close.

PR-URL: nodejs/node#15588
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
  • Loading branch information
ronag authored and addaleax committed Oct 26, 2017
1 parent b4829cd commit d90b9fc
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/_http_client.js
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,6 @@ function socketCloseListener() {
// NOTE: It's important to get parser here, because it could be freed by
// the `socketOnData`.
var parser = socket.parser;
req.emit('close');
if (req.res && req.res.readable) {
// Socket closed before we emitted 'end' below.
req.res.emit('aborted');
Expand All @@ -362,6 +361,7 @@ function socketCloseListener() {
req.socket._hadError = true;
req.emit('error', createHangUpError());
}
req.emit('close');

// Too bad. That output wasn't getting written.
// This is pretty terrible that it doesn't raise an error.
Expand Down
30 changes: 30 additions & 0 deletions test/parallel/test-http-client-close-event.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use strict';
const common = require('../common');

// This test ensures that the `'close'` event is emitted after the `'error'`
// event when a request is made and the socket is closed before we started to
// receive a response.

const assert = require('assert');
const http = require('http');

const server = http.createServer(common.mustNotCall());

server.listen(0, common.mustCall(() => {
const req = http.get({ port: server.address().port }, common.mustNotCall());
let errorEmitted = false;

req.on('error', (err) => {
errorEmitted = true;
assert.strictEqual(err.constructor, Error);
assert.strictEqual(err.message, 'socket hang up');
assert.strictEqual(err.code, 'ECONNRESET');
});

req.on('close', common.mustCall(() => {
assert.strictEqual(errorEmitted, true);
server.close();
}));

req.destroy();
}));

0 comments on commit d90b9fc

Please sign in to comment.