-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
56 lines (36 loc) · 1.03 KB
/
server.js
File metadata and controls
56 lines (36 loc) · 1.03 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
var mongo = require("mongodb").MongoClient;
var client = require("socket.io").listen(6060).sockets;
mongo.connect("mongodb://127.0.0.1/chat", function(err, db){
if(err) throw err;
client.on("connection", function(socket) {
//waiting for inbuts
socket.on("input", function(data){
var name = data.name,
message = data.message,
room = data.room,
whitespacePattern = /^\s*$/;
var col = db.collection(room),
sendStatus = function(s) {
socket.emit("status", s);
};
//Get messages
col.find().limit(100).sort({_id: 1}).toArray(function(err, res) {
if(err) throw err;
socket.emit("output", res);
console.log(room);
});
if(whitespacePattern.test(name) || whitespacePattern.test(message)) {
sendStatus("Name and message required");
} else {
col.insert({name: name, message: message, room: room}, function() {
// Emit latest messages lol
client.emit("output", [data]);
sendStatus({
message: "Message sent",
clear: true
});
});
}
});
});
});