-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
52 lines (47 loc) · 1.31 KB
/
server.js
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
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const bodyParser = require('body-parser');
const path = require('path');
const chatData = [];
const chatStat = new Map();
io.on('connection', (socket) => {
console.log('a user connected')
socket.on('disconnect', () => {
console.log('a user disconnected')
})
})
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json())
app.get('/messages', (req, res) => {
const data = {
chatData,
chatStat: Array.from(chatStat),
}
res.send(JSON.stringify(data))
})
app.post('/new-message', (req, res) => {
const message = addNewMessage(decodeURIComponent(req.body.name), decodeURIComponent(req.body.message));
io.emit('message', message);
res.sendStatus(200);
})
const server = http.listen(3000, () => {
console.log('Server is listening on port ' + server.address().port)
})
const addNewMessage = (name, message) => {
const newMessage = {
name: name,
time: new Date().valueOf(),
text: message,
};
chatData.unshift(newMessage);
message.match(/([^\s]+)/gm).forEach(word => {
if (chatStat.has(word)) {
chatStat.set(word, chatStat.get(word) + 1);
} else {
chatStat.set(word, 1);
};
});
return newMessage;
}