forked from yosuke-furukawa/httpstat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
70 lines (64 loc) · 1.81 KB
/
index.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
const http = require('http');
const https = require('https');
const parse = require('url').parse;
module.exports = function main(arg, opts, headers, data) {
const url = Object.assign(parse(arg), opts);
return new Promise((resolve, reject) => {
const protocol = url.protocol === 'https:' ? https : http;
var begin = Date.now();
var onLookup = begin; // diff begin - dns resolve
var onConnect = begin; // diff dns resolve - connect
var onSecureConnect = begin; // diff connect - secureConnect
var onTransfer = begin; // diff connet - transfer
var onTotal = begin; // diff begin - end
var body = '';
const req = protocol.request(url, (res) => {
res.once('readable', () => {
onTransfer = Date.now();
});
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
onTotal = Date.now();
res.body = body;
resolve({
url: url,
response: res,
time: {
begin: begin,
onLookup: onLookup,
onConnect: onConnect,
onSecureConnect: onSecureConnect,
onTransfer: onTransfer,
onTotal: onTotal,
}
});
});
});
req.on('socket', (socket) => {
socket.on('lookup', () => {
onLookup = Date.now();
});
socket.on('secureConnect', () => {
onSecureConnect = Date.now();
});
socket.on('connect', () => {
onConnect = Date.now();
});
});
req.on('error', reject);
if (headers) {
headers.forEach((header) => {
const entries = header.split(':');
const name = entries[0].trim();
const value = entries[1].trim();
req.setHeader(name, value);
});
}
if (data) {
req.write(data);
}
req.end();
});
}