]> git.cworth.org Git - zombocom-ai/blob - index.js
Write comments out to disk when the server exits
[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 comments = [];
12
13 // Save comments when server is shutting down
14 function cleanup() {
15     fs.writeFileSync('zombocom-state.json', JSON.stringify(comments), (error) => {
16         if (error)
17             throw error;
18     })
19 }
20
21 // And connect to that on either clean exit...
22 process.on('exit', cleanup);
23
24 // ... or on a SIGINT (control-C)
25 process.on('SIGINT', () => {
26     cleanup();
27     process.exit();
28 });
29
30 app.get('/index.html', (req, res) => {
31     res.sendFile(__dirname + '/index.html');
32 });
33
34 io.on('connection', (socket) => {
35     // Replay old comments to a newly-joining client
36     comments.forEach((comment) => {
37         socket.emit('comment', comment)
38     });
39     // When any client comments, send that to all clients (including sender)
40     socket.on('comment', (comment) => {
41         io.emit('comment', comment);
42         comments.push(comment);
43     });
44 });
45
46 server.listen(port, () => {
47     console.log(`listening on *:${port}`);
48 });