diff --git a/lib/_http_client.js b/lib/_http_client.js index 1efdd0f53b..e036522d7b 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -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'); @@ -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. diff --git a/test/parallel/test-http-client-close-event.js b/test/parallel/test-http-client-close-event.js new file mode 100644 index 0000000000..7573931ac4 --- /dev/null +++ b/test/parallel/test-http-client-close-event.js @@ -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(); +}));