Skip to content

Instantly share code, notes, and snippets.

@djanowski
Last active August 29, 2015 14:26
Show Gist options
  • Save djanowski/feaf5eea4da972969695 to your computer and use it in GitHub Desktop.
Save djanowski/feaf5eea4da972969695 to your computer and use it in GitHub Desktop.
// 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