mate-counter/server.js
2018-10-06 16:01:53 +09:30

53 lines
1.3 KiB
JavaScript

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);
json.mates += 1;
fs.writeFile('./mates.json', JSON.stringify(json), (err) => {
if (err)
{
rs.sendStatus(500);
throw err;
}
});
rs.send(json);
});