-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathserver.js
53 lines (48 loc) · 1.86 KB
/
server.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
var port = process.env.PORT || 8000;
var fs = require('fs'); // so we can open the HTML & JS file
var hits = require('./lib/hits'); // our storage interface
var make_svg = require('./lib/make_svg.js');
var extract = require('./lib/extract_request_data.js');
var format = require('./lib/format_hit.js')
var FAVICON = 'http://i.imgur.com/zBEQq4w.png'; // dwyl favicon
var HEAD = require('./lib/headers.json'); // stackoverflow.com/a/2068407/1148249
// plain node.js http server (no fancy framework required!)
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world (test message)' });
socket.on('hello', function (data) {
console.log(data);
});
});
function handler (req, res) {
var url = req.url;
var hit = extract(req);
console.log(hit);
if (url.match(/svg/)) { // only return a badge if SVG requested
hits(hit, function(err, count) {
io.sockets.emit('hit', { 'hit': format(hit, count) }); // broadcast
console.log(url, ' >> ', count); // log in dev
res.writeHead(200, HEAD); // status code and SVG headers
res.end(make_svg(count)); // serve the SVG with count
});
}
else if(url === '/favicon.ico') {
res.writeHead(301, { "Location": FAVICON }); // redirect to @dwyl Favicon
res.end();
}
else if(url === '/client.js') { // these can be cached in "Prod" ...
fs.readFile('./lib/client.js', 'utf8', function (err, data) {
res.writeHead(200, {"Content-Type": "application/javascript"});
res.end(data);
});
}
else { // echo the record without saving it
fs.readFile('./lib/index.html', 'utf8', function (err, data) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(data);
});
}
}
app.listen(port);
console.log('Visit ' + require('./lib/lanip') + ':'+ port);