const express = require("express"), paths = require("./fileManager.js"), blog = require("./blog.js"), path = require("path"), fs = require("fs"), WebSocket = require("ws") const PORT = process.env.PORT || 8090 var app = express() app.use(express.static(paths.data)) var sockets = [] wsServer = WebSocket.Server; let server = require('http').createServer() wsServer = new wsServer({ server: server, perMessageDeflate: false }) server.on('request', app) wsServer.on("connection", function connection(socket) { socket.send(JSON.stringify({ "type": "init" })) function changed() { socket.send(JSON.stringify({type: "allPosts", data: blog.blogPosts()})) } changed() paths.emitter.on("changed", changed) socket.on('message', function message(data) { data = JSON.parse(data) if (data.type == "init") { for (let index = 0; index < sockets.length; index++) { const socketData = sockets[index]; if (socketData.socket == socket) { sockets[index].lastPing = Date.now() } } } else if (data.type == "ping") { socket.send(`{"type": "ping"}`) } else { console.log(data) } }) socket.on("close", () => { console.log("Disconnected") paths.emitter.removeListener("changed", changed) }) sockets.push({ socket, lastPing: Date.now() }) }) server.listen(PORT, function () { console.log("Blog API and WebSocket on port: " + PORT) }) module.exports = { app: app } require("./api.js")