Chapter 10. Activities in Real Time

We are going to be using Node.js’s events library to listen for friend changes from within our channel. This gets us around having to subscribe to multiple channels (which isn’t possible) and opens an avenue for scaling out the chat function using something like Redis or RabbitMQ.

This command tells you how many sockets are in a room:

var clients = io.sockets.clients(

Adding Custom Events

In Chapter 2 you learned about the events library that ships with Node.js. Events are at the core of JavaScript’s power and Node.js makes it easy to create, trigger, and consume everything from I/O progress to user input to custom actions you define yourself in your functions.

Why are custom events so important for real-time notification in the social networking application? After all, you could very easily trigger an event every time someone logs in, updates his status, or comments on someone else’s profile, and let the event handler decide which connected sockets should see the event.

Because Node.js is single-threaded, any logic you do in your event handler will effectively block your running code. So while it might be fast to process a login event if you have only two connections open from your development computer, if you have a real running site your server will be spending a lot of time going through all of the connections to figure out who a particular message should be sent to. That would be a lot of wasted time when it is just ...

Get Building Node Applications with MongoDB and Backbone now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.