server.js
1.39 KB
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
#!/usr/bin/env node
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
var url = require('url');
var fs = require('fs');
var scores = [];
loadScores();
server.listen(port, function() {
console.log('Server listening at port %d', port);
});
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.sendStatus(200);
});
app.get('/addScore', function(req, res) {
var query = url.parse(req.url, true).query;
addScore(parseInt(query.score), query.name);
res.sendStatus(200);
});
io.on('connection', function(socket) {
socket.on('getScores', function() {
socket.emit('scores', scores);
});
});
function loadScores() {
scores = JSON.parse(fs.readFileSync('scores.json', 'utf8'));
}
function saveScores() {
fs.writeFileSync('scores.json', JSON.stringify(scores), 'utf8');
}
function addScore(score, name) {
console.log("SCORE %d by %s", score, name);
var obj = {score: score, name: name};
scores.push(obj);
io.emit('newScore', obj);
saveScores();
}
setInterval(function msg() {
var whole = require('fs').readFileSync('sub.txt', 'utf8');
ex = whole.split('\n');
id = Math.floor((Math.random() * (ex.length - 1)));
io.emit('msg', ex[id])
console.log('MSG', id, ex[id]);
}, 30000);