BlogSharer/exposer.js

71 lines
1.6 KiB
JavaScript
Raw Normal View History

2024-07-06 22:26:22 -05:00
const express = require("express"),
2024-07-07 22:32:52 -05:00
paths = require("./fileManager.js"),
blog = require("./blog.js"),
2024-07-06 22:26:22 -05:00
path = require("path"),
fs = require("fs"),
WebSocket = require("ws")
2024-07-07 22:32:52 -05:00
const PORT = process.env.PORT || 8090
2024-07-06 22:26:22 -05:00
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) {
2024-07-07 22:32:52 -05:00
socket.send(JSON.stringify({
"type": "init"
}))
function changed() {
socket.send(JSON.stringify({type: "allPosts", data: blog.blogPosts()}))
}
changed()
paths.emitter.on("changed", changed)
2024-07-06 22:26:22 -05:00
socket.on('message', function message(data) {
data = JSON.parse(data)
2024-07-07 22:32:52 -05:00
if (data.type == "init") {
2024-07-06 22:26:22 -05:00
for (let index = 0; index < sockets.length; index++) {
const socketData = sockets[index];
if (socketData.socket == socket) {
sockets[index].lastPing = Date.now()
}
}
2024-07-07 22:32:52 -05:00
} else if (data.type == "ping") {
socket.send(`{"type": "ping"}`)
}
else {
2024-07-06 22:26:22 -05:00
console.log(data)
}
})
2024-07-07 22:32:52 -05:00
socket.on("close", () => {
console.log("Disconnected")
paths.emitter.removeListener("changed", changed)
})
2024-07-06 22:26:22 -05:00
sockets.push({ socket, lastPing: Date.now() })
})
2024-07-06 22:38:13 -05:00
server.listen(PORT, function () {
console.log("Blog API and WebSocket on port: " + PORT)
})
2024-07-06 22:26:22 -05:00
module.exports = {
app: app
}
require("./api.js")