You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.3 KiB

11 years ago
'use strict';
var http = require('http');
var https = require('https');
var urlLib = require('url');
var zlib = require('zlib');
var PassThrough = require('stream').PassThrough;
var assign = require('object-assign');
11 years ago
module.exports = function (url, opts, cb) {
if (typeof opts === 'function') {
// if `cb` has been specified but `opts` has not
cb = opts;
opts = {};
} else if (!opts) {
// opts has not been specified
opts = {};
}
11 years ago
10 years ago
// extract own options
var encoding = opts.encoding;
delete opts.encoding;
// returns a proxy stream to the response
// if no callback has been provided
var proxy;
if (!cb) {
proxy = new PassThrough();
11 years ago
// forward errors on the stream
cb = function (err) {
proxy.emit('error', err);
};
}
// merge additional headers
opts.headers = assign({
'user-agent': 'https://github.com/sindresorhus/got',
'accept-encoding': 'gzip,deflate'
}, opts.headers || {});
var redirectCount = 0;
var get = function (url, opts, cb) {
var parsedUrl = urlLib.parse(url);
var fn = parsedUrl.protocol === 'https:' ? https : http;
var arg = assign({}, parsedUrl, opts);
fn.get(arg, function (res) {
11 years ago
// redirect
if (res.statusCode < 400 && res.statusCode >= 300 && res.headers.location) {
res.destroy();
11 years ago
if (++redirectCount > 10) {
cb(new Error('Redirected 10 times. Aborting.'));
return;
}
get(urlLib.resolve(url, res.headers.location), opts, cb);
11 years ago
return;
}
if (res.statusCode < 200 || res.statusCode > 299) {
res.destroy();
11 years ago
cb(res.statusCode);
return;
}
if (['gzip', 'deflate'].indexOf(res.headers['content-encoding']) !== -1) {
var unzip = zlib.createUnzip();
res.pipe(unzip);
res = unzip;
}
// pipe the response to the proxy if in proxy mode
if (proxy) {
res.pipe(proxy);
res.on('error', function forwardError(error) {
proxy.emit('error', error);
})
return;
}
res.once('error', cb);
11 years ago
var chunks = [];
10 years ago
var len = 0;
11 years ago
res.on('data', function (chunk) {
chunks.push(chunk);
10 years ago
len += chunk.length;
});
res.once('end', function () {
10 years ago
var data = Buffer.concat(chunks, len);
if (encoding !== null) {
data = data.toString(encoding || 'utf8');
}
cb(null, data, res);
11 years ago
});
}).once('error', cb);
11 years ago
};
get(url, opts, cb);
return proxy;
11 years ago
};