Browse Source

Merge pull request #14 from floatdrop/timeout

Add timeout option
http2
Sindre Sorhus 10 years ago
parent
commit
a0b907c561
  1. 7
      index.js
  2. 7
      package.json
  3. 6
      readme.md
  4. 9
      test.js

7
index.js

@ -6,6 +6,7 @@ var zlib = require('zlib');
var PassThrough = require('stream').PassThrough; var PassThrough = require('stream').PassThrough;
var assign = require('object-assign'); var assign = require('object-assign');
var read = require('read-all-stream'); var read = require('read-all-stream');
var timeout = require('timed-out');
module.exports = function (url, opts, cb) { module.exports = function (url, opts, cb) {
if (typeof opts === 'function') { if (typeof opts === 'function') {
@ -46,7 +47,7 @@ module.exports = function (url, opts, cb) {
var fn = parsedUrl.protocol === 'https:' ? https : http; var fn = parsedUrl.protocol === 'https:' ? https : http;
var arg = assign({}, parsedUrl, opts); var arg = assign({}, parsedUrl, opts);
fn.get(arg, function (response) { var req = fn.get(arg, function (response) {
var statusCode = response.statusCode; var statusCode = response.statusCode;
var res = response; var res = response;
@ -84,6 +85,10 @@ module.exports = function (url, opts, cb) {
read(res, encoding, cb, response); read(res, encoding, cb, response);
}).once('error', cb); }).once('error', cb);
if (opts.timeout) {
timeout(req, opts.timeout);
}
}; };
get(url, opts, cb); get(url, opts, cb);

7
package.json

@ -13,8 +13,7 @@
"node": ">=0.10.0" "node": ">=0.10.0"
}, },
"scripts": { "scripts": {
"test": "mocha", "test": "mocha"
"coverage": "istanbul cover _mocha -- -R spec"
}, },
"files": [ "files": [
"index.js" "index.js"
@ -33,10 +32,10 @@
], ],
"dependencies": { "dependencies": {
"object-assign": "^1.0.0", "object-assign": "^1.0.0",
"read-all-stream": "^0.1.0" "read-all-stream": "^0.1.0",
"timed-out": "^1.0.0"
}, },
"devDependencies": { "devDependencies": {
"istanbul": "^0.3.2",
"mocha": "*" "mocha": "*"
} }
} }

6
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. 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) ##### callback(err, data, response)
###### err ###### err

9
test.js

@ -90,3 +90,12 @@ it('should proxy errors to the stream', function (done) {
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();
});
});

Loading…
Cancel
Save