-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
56 lines (38 loc) · 1.02 KB
/
app.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
53
54
55
56
//// REQUIRES ////
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var mongoose = require('mongoose');
//// DEFINE MONGODB MODEL ////
var db = mongoose.connect('mongodb://localhost/chatapp');
var Schema = mongoose.Schema;
var msgSchema = Schema({
name : String,
data : String
});
var Msg = db.model('Message', msgSchema);
//// CHAT SOCKET.IO ////
var io = require('socket.io').listen(server);
io.on('connection', function(client){
// when a chat message is sent from the client
client.on('chat message', function(msg){
io.emit('chat message', msg);
Msg.create({
name: msg.name,
data: msg.data
});
});
// when a user joins the chat
client.on('join', function(name){
io.emit('join', name);
// emit previously stored messages to the client
Msg.find({}).exec(function(err, msgs){
msgs.forEach(function(m){
client.emit('chat message',m);
});
});
});
});
//// ROUTING ////
app.use(express.static(__dirname));
server.listen(3000);