Skip to content

Instantly share code, notes, and snippets.

@djanowski djanowski/time.js Secret
Last active Aug 29, 2015

Embed
What would you like to do?
// Determines the current time (with a +/- 1 second tolerance)
// by making HTTP requests to the hosts specified in hostnames.txt.
//
// Assumes unanimity. If a single host's clock is off by more than
// two seconds, it'll invalidate the whole operation.
//
// $ node time.js
const fs = require('fs');
const http = require('http');
function getDateFromHost(hostname) {
return new Promise(function(resolve, reject) {
http.get({ hostname }, function(res) {
resolve(res.headers.date);
}).on('error', reject);
});
}
function guessTimeFromInterwebz(hostnames) {
return Promise.all(hostnames.map(getDateFromHost))
.then(function(dates) {
const times = dates
.filter(function(d) { return !!d; })
.map( function(d) { return (new Date(d)).getTime() });
const min = Math.min.apply(Math, times);
const max = Math.max.apply(Math, times);
const diff = max - min;
if (diff <= 2000)
return new Date((min + max) / 2);
else
return null;
})
}
const hostnames = fs.readFileSync('hostnames.txt')
.toString()
.split("\n")
.filter(function(line) {
return line.length > 0;
});
guessTimeFromInterwebz(hostnames)
.then(function(time) {
if (time)
console.log(time.toISOString());
else
console.error('Could not accurately determine the time.');
})
.catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.