diff --git a/index.js b/index.js index 4e22938..0467fc6 100644 --- a/index.js +++ b/index.js @@ -1,15 +1,44 @@ const express = require('express'); -const app = express(); +const path = require('path'); +const { WebSocketServer } = require('ws'); +const { createServer } = require('http'); +const fs = require('fs'); + const config = require('./config.json'); +let clients = []; + +const app = express(); +const server = createServer(app); +const wss = new WebSocketServer({ server }); + +wss.on('connection', function connection(ws) { + clients.push(ws); + ws.on('close', () => { + clients.pop(ws); + }); +}); + +// auto refresh on frontend update +let lastUpdateTime = Date.now(); +fs.watch('./ejs/', () => { + const now = Date.now(); + if (now - lastUpdateTime > 50) { + clients.forEach((ws) => { + ws.send('update'); + }); + } + lastUpdateTime = now; +}); app.use(express.json()); app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'ejs')); + app.get('/', (req, res) => { res.render('home'); }); -app.listen(config.port, () => { +server.listen(config.port, () => { console.log(`Server started on port ${config.port}`); }); \ No newline at end of file