var fs = require('fs'); // Filesystem var express = require('express'); // Express var bodyParser = require('body-parser'); // Data conversion, JSON parsing // Set up Express var app = express(); app.use(express.static("./")); // Serve static files from root app.use(express.json()); // Parse JSON in requests // app.use("/", (req, res, next) => // Finally send a 404 page // { // res.status(404).sendFile("404.html", {"root": "./"}); // }); // Root route, respond with with index.html app.get("/", function(req, res) { res.sendFile("./index.html"); }); // Posts route, return posts.json app.get("/posts", function(req, res) { res.json(JSON.parse(fs.readFileSync('./data/posts.json'))); }); // Posts route, digest received post app.post("/posts", function(req, res) { var postsFile = fs.readFileSync('./data/posts.json'); var posts = JSON.parse(postsFile); var incomingData = req.body; if (validatePost(incomingData)) { posts.unshift(incomingData); } else { res.status(400).json({"error":"Failed to validate post"}); return; } fs.writeFile('./data/posts.json', JSON.stringify(posts), (e) => { if (e) { res.sendStatus(500); throw e; } }); res.sendStatus(204); }); // About route, return about.json app.get("/about", (req, res) => { res.json(JSON.parse(fs.readFileSync('./data/about.json'))); }); // Start listening app.listen(8080, function() { console.log("Listening on port 8080"); }); // Validates a post object conforms to the standard we're expecting function validatePost(post) { try { // Check types of each expected property and assume they're there return (typeof post.title === "string" && typeof post.author === "string" && typeof post.date === "number" && Array.isArray(post.tags) && typeof post.content === "string"); } catch (e) { // Object clearly isn't what we're expecting return false; } }