]> git.cworth.org Git - zombocom-ai/blob - index.js
And now read in saved comments at server start
[zombocom-ai] / index.js
1 const fs = require('fs');
2
3 const express = require('express');
4 const app = express();
5 const http = require('http');
6 const server = http.createServer(app);
7 const { Server } = require("socket.io");
8 const io = new Server(server);
9 const port = 2122;
10
11 const state_file = 'zombocom-state.json'
12
13 var comments;
14
15 // Load comments at server startup
16 fs.readFile(state_file, (err, data) => {
17     if (err)
18         comments = [];
19     else
20         comments = JSON.parse(data);
21 });
22
23 // Save comments when server is shutting down
24 function cleanup() {
25     fs.writeFileSync('zombocom-state.json', JSON.stringify(comments), (error) => {
26         if (error)
27             throw error;
28     })
29 }
30
31 // And connect to that on either clean exit...
32 process.on('exit', cleanup);
33
34 // ... or on a SIGINT (control-C)
35 process.on('SIGINT', () => {
36     cleanup();
37     process.exit();
38 });
39
40 app.get('/index.html', (req, res) => {
41     res.sendFile(__dirname + '/index.html');
42 });
43
44 io.on('connection', (socket) => {
45     // Replay old comments to a newly-joining client
46     comments.forEach((comment) => {
47         socket.emit('comment', comment)
48     });
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);
53     });
54 });
55
56 server.listen(port, () => {
57     console.log(`listening on *:${port}`);
58 });