1 const fs = require('fs');
3 const express = require('express');
5 const http = require('http');
6 const server = http.createServer(app);
7 const { Server } = require("socket.io");
8 const io = new Server(server);
11 const state_file = 'zombocom-state.json'
15 // Load comments at server startup
16 fs.readFile(state_file, (err, data) => {
20 comments = JSON.parse(data);
23 // Save comments when server is shutting down
25 fs.writeFileSync('zombocom-state.json', JSON.stringify(comments), (error) => {
31 // And connect to that on either clean exit...
32 process.on('exit', cleanup);
34 // ... or on a SIGINT (control-C)
35 process.on('SIGINT', () => {
40 app.get('/index.html', (req, res) => {
41 res.sendFile(__dirname + '/index.html');
44 io.on('connection', (socket) => {
45 // Replay old comments to a newly-joining client
46 comments.forEach((comment) => {
47 socket.emit('comment', comment)
49 // When any client comments, send that to all clients (including sender)
50 socket.on('comment', (comment) => {
51 io.emit('comment', comment);
52 comments.push(comment);
56 server.listen(port, () => {
57 console.log(`listening on *:${port}`);