-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
76 lines (57 loc) · 1.58 KB
/
server.js
File metadata and controls
76 lines (57 loc) · 1.58 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
69
70
71
72
73
74
75
76
const http = require("http");
const fs = require("fs").promises;
const HttpDispatcher = require('httpdispatcher');
var dispatcher = new HttpDispatcher()
const port = 3000;
const requestListener = (req, res) => {
try {
dispatcher.dispatch(req, res);
} catch (error) {
console.log(error);
}
}
const server = http.createServer(requestListener);
dispatcher.onGet("/", function(req, res) {
fs.readFile(__dirname + "/index.html")
.then((contents) => {
res.setHeader("Content-Type", "text/html");
res.writeHead(200);
res.end(contents);
})
});
dispatcher.onGet("/login", function(req, res) {
fs.readFile(__dirname + "/login.html")
.then((contents) => {
res.setHeader("Content-Type", "text/html");
res.writeHead(200);
res.end(contents);
})
});
dispatcher.onError(function(req, res) {
res.writeHead(404);
res.end("Error, the URL doesn't exist");
});
const io = require('socket.io')(server);
io.on('connection', client => {
fs.readFile(__dirname + '/db.json', 'utf8')
.then((res) => {
let datas = { chat: [] }
if (res) datas = JSON.parse(res)
io.emit('datas', datas.chat)
})
client.on('chat', (msg) => {
io.emit('chat', msg);
fs.readFile(__dirname + '/db.json', 'utf8')
.then((res) => {
let datas = res ? JSON.parse(res) : {}
if (!datas.chat) datas.chat = []
datas.chat.push(msg)
fs.writeFile(__dirname + '/db.json', JSON.stringify(datas))
io.emit('datas', datas.chat ? datas.chat : [])
})
})
client.on('disconnect', () => {
console.log('User disconnect !')
});
});
server.listen(process.env.PORT || port)