var bodyParser = require('body-parser'); // Data conversion, JSON parsing var express = require('express'); var https = require('https'); var http = require('http'); var path = require('path'); var fs = require('fs'); // Set up Express ////////////////////////////////////////////////////////////// var app = express(); app.use(express.static("./")); // Set root as current dir app.use(express.json()); // Use JSON handler when parsing requests // Set up server and start listening /////////////////////////////////////////// http.createServer(app).listen(8000); // https.createServer(options, app).listen(443); // Add routes ////////////////////////////////////////////////////////////////// // Get root app.get('/', function(rq, rs) { rs.sendFile('./index.html') }); // Get mates count app.get('/mates', function(rq, rs) { var data = fs.readFileSync('./mates.json'); var json = JSON.parse(data); rs.send(json); }); // Update mates count app.post('/mates', function(rq, rs) { var data = fs.readFileSync('./mates.json'); var json = JSON.parse(data); var cooldownSecs = 60; var currentTime = new Date().getTime(); var timeSinceLast = (currentTime - json.lastUpdate) / 1000; // Check if update was sent too quickly if (timeSinceLast < cooldownSecs) { rs .status(403) .json({ error:"Update sent too quickly", cooldown: cooldownSecs, remaining: Math.ceil(cooldownSecs - timeSinceLast) }); return; } json.mates += 1; json.lastUpdate = new Date().getTime(); fs.writeFile('./mates.json', JSON.stringify(json), (err) => { if (err) { rs.sendStatus(500); throw err; } }); rs.send(json); });