-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
68 lines (57 loc) · 1.79 KB
/
server.js
File metadata and controls
68 lines (57 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "http://localhost:3000", // Allow WebSocket connections from localhost:3000
methods: ["GET", "POST"]
}
});
const PORT = 5500;
// Middleware
app.use(bodyParser.json());
app.use(express.static('public'));
// Endpoint to handle form submission
app.post('/submit', (req, res) => {
const data = req.body;
fs.readFile('data.json', (err, fileData) => {
if (err) {
console.error(err);
return res.status(500).send('Error reading data file');
}
const jsonData = fileData.length ? JSON.parse(fileData) : [];
jsonData.push(data);
fs.writeFile('data.json', JSON.stringify(jsonData, null, 2), (err) => {
if (err) {
console.error(err);
return res.status(500).send('Error writing to data file');
}
res.status(200).send('Data saved successfully');
// Send data update to frontend on localhost:3000
io.emit('emergencyUpdate', jsonData);
});
});
});
// Endpoint to retrieve stored data
app.get('/data', (req, res) => {
fs.readFile('data.json', (err, fileData) => {
if (err) {
console.error(err);
return res.status(500).send('Error reading data file');
}
res.json(JSON.parse(fileData));
});
});
// WebSocket connection handler
io.on('connection', (socket) => {
console.log('Dashboard connected:', socket.id);
});
// Start the server
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});