forked from jamesrom/Forked
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
98 lines (87 loc) · 2.16 KB
/
app.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
var express = require('express');
var http = require('http');
var fs = require('fs');
var app = express();
app.get('/:height?', function(req, res) {
console.log('request made');
var page;
var info = {};
function buildPage() {
if (!info.count || !page) {
return;
}
if (info.count > 0) {
page = page.replace(/\{YESNO\}/g, info.count > 1 ? '<h1 class="yes">YES</h1>' : '<h1 class="no">NO</h1>');
page = page.replace(/\{BLOCK_DESC\}/g, info.count != 1 ? info.count + " blocks" : "Only one block");
page = page.replace(/\{HEIGHT\}/g, info.height);
res.send(page);
}
else {
page = page.replace(/\{YESNO\}/g, '<h1>WAT</h1>');
page = page.replace(/\{BLOCK_DESC\}/g, 'Zero blocks');
page = page.replace(/\{HEIGHT\}/g, info.height);
res.send(page);
}
}
fs.readFile(__dirname + '/static/index.html', 'utf8', function (err, data) {
if (err) {
res.send("Error");
return;
}
page = data;
// just incase fs is slower than http for some reason
buildPage();
});
// handle height parameter
if (req.params.height) {
info.height = parseInt(req.params.height);
if (!isNaN(info.height)) {
blocksAtHeight(info.height, function(count) {
info.count = count;
buildPage();
});
return;
}
}
latestHeight(function(height) {
info.height = height;
blocksAtHeight(height, function(count) {
info.count = count;
buildPage();
});
});
});
function latestHeight(callback) {
var url = 'http://blockchain.info/latestblock';
http.get(url, function(res) {
accumulate(res, function(body) {
callback(JSON.parse(body).height);
});
});
}
function blocksAtHeight(height, callback) {
var url = 'http://blockchain.info/block-height/' + height + '?format=json';
http.get(url, function(res) {
accumulate(res, function(body) {
try {
var count = JSON.parse(body).blocks.length;
callback(count);
}
catch(ex) {
callback(-1);
}
});
});
}
function accumulate(response, callback) {
var body = '';
response.on('data', function(chunk) {
body += chunk;
});
response.on('end', function() {
callback(body);
});
}
app.use(express.static(__dirname + '/static'));
app.listen(80);
console.log('listening on port 80');