diff --git a/index.js b/index.js index ce2b974..ad3ec63 100644 --- a/index.js +++ b/index.js @@ -6,6 +6,7 @@ var zlib = require('zlib'); var PassThrough = require('stream').PassThrough; var assign = require('object-assign'); var read = require('read-all-stream'); +var timeout = require('timed-out'); module.exports = function (url, opts, cb) { if (typeof opts === 'function') { @@ -46,7 +47,7 @@ module.exports = function (url, opts, cb) { var fn = parsedUrl.protocol === 'https:' ? https : http; var arg = assign({}, parsedUrl, opts); - fn.get(arg, function (response) { + var req = fn.get(arg, function (response) { var statusCode = response.statusCode; var res = response; @@ -84,6 +85,10 @@ module.exports = function (url, opts, cb) { read(res, encoding, cb, response); }).once('error', cb); + + if (opts.timeout) { + timeout(req, opts.timeout); + } }; get(url, opts, cb); diff --git a/package.json b/package.json index 30c567d..1460302 100644 --- a/package.json +++ b/package.json @@ -13,8 +13,7 @@ "node": ">=0.10.0" }, "scripts": { - "test": "mocha", - "coverage": "istanbul cover _mocha -- -R spec" + "test": "mocha" }, "files": [ "index.js" @@ -33,10 +32,10 @@ ], "dependencies": { "object-assign": "^1.0.0", - "read-all-stream": "^0.1.0" + "read-all-stream": "^0.1.0", + "timed-out": "^1.0.0" }, "devDependencies": { - "istanbul": "^0.3.2", "mocha": "*" } } diff --git a/readme.md b/readme.md index bfb52d2..1f2fd6d 100644 --- a/readme.md +++ b/readme.md @@ -57,6 +57,12 @@ Default: `'utf8'` Encoding to be used on `setEncoding` of the response data. If null, the body is returned as a Buffer. +##### options.timeout + +Type: `number` + +Time in ms, after which request will be aborted and error event with `ETIMEDOUT` code will be emitted. + ##### callback(err, data, response) ###### err diff --git a/test.js b/test.js index 36ea558..a72f45b 100644 --- a/test.js +++ b/test.js @@ -90,3 +90,12 @@ it('should proxy errors to the stream', function (done) { done(); }); }); + +it('should support timeout option', function (done) { + var stream = got('http://sindresorhus.com/', { timeout: 1 }); + + stream.on('error', function (error) { + assert.strictEqual(error.code, 'ETIMEDOUT'); + done(); + }); +});