-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
http.js
80 lines (64 loc) · 1.87 KB
/
http.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
'use strict';
var ProbeError = require('./lib/common').ProbeError;
var needle = require('needle');
var lodashMerge = require('lodash.merge');
var pkg = require('./package.json');
var probeStream = require('./stream');
var URL = require('url').URL;
var defaultAgent = pkg.name + '/' + pkg.version + '(+https://github.com/nodeca/probe-image-size)';
var defaults = {
open_timeout: 10000,
response_timeout: 60000,
read_timeout: 60000,
follow_max: 10,
parse_response: false,
// Use to ignore bad certificates.
//rejectUnauthorized: false,
headers: {
'User-Agent': defaultAgent
}
};
module.exports = function probeHttp(src, options) {
return new Promise(function (resolve, reject) {
var stream, len, finalUrl = src;
try {
var needleOptions = lodashMerge({}, defaults, options);
stream = needle.get(src, needleOptions);
} catch (err) {
reject(err);
return;
}
stream.on('redirect', function (location) {
try {
finalUrl = new URL(location, finalUrl).href;
} catch (err) {
reject(err);
stream.request.abort();
}
});
stream.on('header', function (statusCode, headers) {
if (statusCode !== 200) {
reject(new ProbeError('bad status code: ' + statusCode, null, statusCode));
stream.request.abort();
return;
}
len = headers['content-length'];
});
stream.on('err', function (err) {
reject(err);
stream.request.abort();
});
probeStream(stream, true)
.then(function (result) {
if (len && len.match(/^\d+$/)) result.length = +len;
result.url = finalUrl;
resolve(result);
stream.request.abort();
})
.catch(function (err) {
reject(err);
stream.request.abort();
});
});
};
module.exports.parsers = require('./lib/parsers_stream');