-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcardfax.js
67 lines (55 loc) · 1.47 KB
/
cardfax.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
/*
A little nodejs server that accepts http requests like
http://localhost:1337/match?win=WinningAwsomeProgramName&lose=PitifulLoserProgram
and you can go to
http://localhost:1337/
also to view the total scores (+1 per victory, -1 per loss)
*/
var fs = require('fs');
var http = require('http');
var url = require('url');
var matches = {};
var scores = {};
var dataFile = '/tmp/data.json';
fs.readFile(dataFile, readHandler) ;
function readHandler (err, data) {
if (err) {
console.log(err);
}
else {
var j = JSON.parse(data);
matches = j[0];
scores = j[1];
}
}
function saveScores() {
fs.writeFile(dataFile, JSON.stringify([matches, scores]));
}
function showScores(res) {
res.write('<html><body><table>');
for (var x in scores) {
res.write('<tr><td>' + x + '</td><td>' + scores[x] + '</td></tr>');
}
res.write('</table></body></html>');
}
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var r = url.parse(req.url, true);
if (r.pathname === '/match') {
var win = r.query.win;
var lose = r.query.lose;
var name = win + "," + lose;
if (!matches[name]) {
matches[name] = 1;
scores[win] = (scores[win] ? scores[win] : 0) + 1;
scores[lose] = (scores[lose] ? scores[lose] : 0) - 1;
saveScores();
}
showScores(res);
}
if (r.pathname === '/') {
showScores(res);
}
res.end('');
}).listen(1337, 'localhost');
console.log('Server running.');