diff --git a/lib/_http_client.js b/lib/_http_client.js index 603d37de9b19a6..c4259184a6c5b3 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -655,7 +655,10 @@ function tickOnSocket(req, socket) { socket.on('end', socketOnEnd); socket.on('close', socketCloseListener); - if (req.timeout !== undefined) { + if ( + req.timeout !== undefined || + (req.agent && req.agent.options && req.agent.options.timeout) + ) { listenSocketTimeout(req); } req.emit('socket', socket); diff --git a/test/parallel/test-http-agent-timeout-option.js b/test/parallel/test-http-agent-timeout-option.js new file mode 100644 index 00000000000000..4fcfc1f1da54b1 --- /dev/null +++ b/test/parallel/test-http-agent-timeout-option.js @@ -0,0 +1,23 @@ +'use strict'; + +const { expectsError, mustCall } = require('../common'); +const { Agent, get } = require('http'); + +// Test that the `'timeout'` event is emitted on the `ClientRequest` instance +// when the socket timeout set via the `timeout` option of the `Agent` expires. + +const request = get({ + agent: new Agent({ timeout: 500 }), + // Non-routable IP address to prevent the connection from being established. + host: '192.0.2.1' +}); + +request.on('error', expectsError({ + type: Error, + code: 'ECONNRESET', + message: 'socket hang up' +})); + +request.on('timeout', mustCall(() => { + request.abort(); +}));