From: Carl Worth <cworth@cworth.org>
Date: Wed, 7 Dec 2022 05:39:24 +0000 (-0800)
Subject: Write comments out to disk when the server exits
X-Git-Url: https://git.cworth.org/git?a=commitdiff_plain;h=4b6741491ea2b312f9ef93b13da4af525ec75b5a;p=zombocom-ai

Write comments out to disk when the server exits

Which is half of what we need for fully persistent messages, (will
need to also load them at startup).
---

diff --git a/index.js b/index.js
index 80526a3..9279c87 100644
--- a/index.js
+++ b/index.js
@@ -1,3 +1,5 @@
+const fs = require('fs');
+
 const express = require('express');
 const app = express();
 const http = require('http');
@@ -8,6 +10,23 @@ const port = 2122;
 
 comments = [];
 
+// Save comments when server is shutting down
+function cleanup() {
+    fs.writeFileSync('zombocom-state.json', JSON.stringify(comments), (error) => {
+        if (error)
+            throw error;
+    })
+}
+
+// And connect to that on either clean exit...
+process.on('exit', cleanup);
+
+// ... or on a SIGINT (control-C)
+process.on('SIGINT', () => {
+    cleanup();
+    process.exit();
+});
+
 app.get('/index.html', (req, res) => {
     res.sendFile(__dirname + '/index.html');
 });