-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
51 lines (38 loc) · 1.14 KB
/
Copy pathserver.js
File metadata and controls
51 lines (38 loc) · 1.14 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
// JavaScript Document
var mongo = require("mongodb").MongoClient;
var client = require('socket.io').listen(8080).sockets;
mongo.connect('mongodb://127.0.0.1/chat', function(err, db){
if(err) throw err;
client.on('connection', function(socket){
var col = db.collection('messages'),
sendStatus = function(statusMsg){
socket.emit('status', statusMsg);
};
//Display all the messages from Monogo DB
col.find().limit(100).sort({_id: 1}).toArray(function(err, res){
if(err) throw err;
socket.emit('output', res);
});
//Wai for input
socket.on('input', function(data){
var name = data.name;
var message = data.message;
//Regular Expression to identify the whitespace
var whitespacePattern = /^\s*$/;
if(whitespacePattern.test(name) ||
whitespacePattern.test(message)){
console.log("not inserted");
sendStatus('Name and message is required');
}else{
col.insert({name:name, message:message}, function(){
//Emit latest messages to all clients
client.emit('output', [data]);
sendStatus({
message: "Message sent",
clear:true
});
});
}
});
});
});