From: Raphaƫl Jakse Date: Sun, 5 Apr 2020 20:00:07 +0000 (+0200) Subject: More defensively save games when closing X-Git-Url: https://secure.softndesign.org/git/?a=commitdiff_plain;h=041f40b89b85cbcc01bb59898caf2827eb2442e9;p=trivabble.git More defensively save games when closing --- diff --git a/trivabble-server.js b/trivabble-server.js index 530495f..24f6b5f 100644 --- a/trivabble-server.js +++ b/trivabble-server.js @@ -115,16 +115,14 @@ let saveTimeout = null; let running = true; const server = http.createServer(handleRequest); -function saveGames(exit) { +function saveGames(callback) { fs.writeFile("games.backup.json", JSON.stringify(games), function (err) { if (err) { console.error("ERROR: Cannot save games!"); - } else if (exit) { - console.log("Games saved."); } - if (exit) { - server.close(); + if (typeof callback === "function") { + return callback(err); } }); @@ -153,26 +151,34 @@ function writeResponse(responseAndIsES, data, terminate) { } function stop() { - running = false; - console.log("Closing connections and saving the game state..."); + console.log("Saving games a first time"); + if (saveTimeout) { + clearTimeout(saveTimeout); + saveTimeout = null; + } - let listeningPlayerCount = 0; - let gamesCount = 0; + saveGames(function () { + running = false; + console.log("Closing connections and saving the game state..."); - for (const gameID of Object.keys(games)) { - const game = games[gameID]; - for (const listeningPlayer of game.listeningPlayers) { - writeResponse(listeningPlayer, '{"stopping": 2000}', true); - } + let listeningPlayerCount = 0; + let gamesCount = 0; + + for (const gameID of Object.keys(games)) { + const game = games[gameID]; + for (const listeningPlayer of game.listeningPlayers) { + writeResponse(listeningPlayer, '{"stopping": 2000}', true); + } - if (game.listeningPlayers.length) { - listeningPlayerCount += game.listeningPlayers.length; - gamesCount++; + if (game.listeningPlayers.length) { + listeningPlayerCount += game.listeningPlayers.length; + gamesCount++; + } } - } - console.log("Stopped", gamesCount, "games and", listeningPlayerCount, "player connections."); - saveGames(true); + console.log("Stopped", gamesCount, "games and", listeningPlayerCount, "player connections."); + server.close(saveGames); + }); } function stopKeepAlive(responseAndIsES) {