-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.js
105 lines (85 loc) · 2.65 KB
/
time.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
const http = require('http');
const File = require('fs');
const Path = require('path');
// We make parallel requests to list of servers and calculate the average of
// all server time responses for the current time. We then calculate the
// latency (endTime - startime) and add it to the current time(avg time) in order to
// get a more accurate time. Script prints out the time in ISO 8601
// format to the console
const startTime = Date.now();
checkAllServersInParallel('hostnames.txt')
.then(function(data) {
const avgTime = getAverageTime(data); // avg time of all server times
const latency = Date.now() - startTime; // add latency to average
const avgTimePlusLatency = new Date(avgTime + latency);
console.log(`Date: ${avgTimePlusLatency}.`);
console.log(`Time in ISO 8601: ${avgTimePlusLatency.toISOString()}`);
})
.catch(error => console.log(error));
// Returns a promise that resolves when all servers are checked.
function checkAllServersInParallel(filename) {
const listOfServers = getListOfServers(filename);
const promisedServerResponses = listOfServers.map(server => checkServer(server));
const dateResultsAsync = Promise.all(promisedServerResponses);
return dateResultsAsync;
}
// Returns a promise
function checkServer(server) {
return httpGet(server)
.then(function(res) {
if(res.headers.date) {
let d = new Date(res.headers.date); //convert to local time
// console.log('server and resp date: ', server, res.headers.date);
let timeInMs = d.getTime(); // get time in ms
return { timeInMs };
}
})
.catch(function(error) {
console.log(error);
return error;
});
}
function httpGet(server) {
return new Promise(function(resolve, reject) {
http.get(server, function(res, error) {
if (res)
resolve(res);
else
reject(error);
});
});
}
// Averages the time in ms from all servers responses.
function getAverageTime(results) {
let total = 0;
let validResults = 0;
results.forEach(function(result) {
if (result && result.timeInMs){
total += result.timeInMs;
validResults++;
}
});
const avgTime = total / validResults;
return avgTime;
}
function getListOfServers(filename) {
function notEmpty(line) {
return line.trim().length > 0;
}
function notAComment(line) {
return line[0] !== '#';
}
function dropComment(line) {
return line.replace(/\s+#.*/, '');
}
function fixUrl(line) {
return `http://${line}`;
}
const fullname = Path.resolve(__dirname, filename);
return File.readFileSync(fullname, 'utf8')
.split('\n')
.filter(notEmpty)
.filter(notAComment)
.map(dropComment)
.map(fixUrl);
}