Posted on by & filed under Content - Highlights and Reviews, Programming & Development.

A guest post by Pedro Teixeira, a geek, programmer, freelancer, and entrepreneur. He is the author of some Node.js modules, the Node Tuts screencast show, some books about Node.js and overall fervent proclaimer of the Node.js creed. He is also the Co-founder and Partner of The Node Firm, and the organizer of the Lisbon JavaScript Conference.

In a previous post titled Node.js and Websockets: A Modular Approach, we looked at how to use Node.js as a websocket server and connect a browser to it, exchanging events in either direction using the websocket stream.

In this post, we will cover the same pattern to build a simple web application that lets two or more users collaborate in real time.

As an example, we will be building a simple to-do app. Each to-do list will have a unique URL, and any user with access to that URL will be able to edit the to-do items on that list and observe, in real-time, the changes that other users are also doing, keeping all the states in the different browsers in sync.

We will be using some tools that we already covered in the Node.js and Websockets post, so I advise you to read it if you haven’t already. You will find the source code for this post here:

The final code can be found in this github repo. You can clone it and refer to it if you are following along and get lost.

A Bit About the Architecture

The browser client will be a single page application. When the user enters a to-do list URL, the application loads and connects to our websocket server in Node.js. From then on, the application will emit events to the server.

The server will then propagate the relevant events coming from a user in a given to-do list to all the users that are working on that list. For instance, when a user creates a to-do item, that event propagates to the server. The server will immediately broadcast that event to all the connected users that are listening on that to-do list, making the state of the to-do list update in real time.

The App Skeleton

To start off we need to setup the application skeleton. For that, you can download the code from this Github repo. It contains the base for the application using Bootstrap, jQuery and AngularJS. The static files are served by a static Node.js HTTP server.

Once you have that repo downloaded, you can cd into it and install the missing NPM dependencies:

The Store

Once you have that, you’ll need some place to store the application to-do items. To simplify we’ll just store these in memory, and for that we can create the store.js local module in the root directory of the project:

This module simply provides a basic create, get and remove directives for lists. The creation of a list uses the node-uuid module to create a unique identifier for a list.

Creating a New List

When going to the base URL for the website, the user is presented with a link to create a new to-do list. When clicking on that link, AngularJS looks for a controller named NewListCtrl. Let’s create it under browser/js/controllers/new_list.js:

Without going into too much detail of how AngularJS works, I can tell you that this controller makes an HTTP request to the /lists/new URL and expects the server to reply with a list ID. Currently our Node.js server does not support this action, so we need to change index.js and add the following around line 17:

We also need to include the store module at the top of that same file:

To make this work we need to use browserify to create an application bundle for the browser. We already have a bash script under bin/browserify that does that. If you have a Windows environment, you can easily create a .bat alternative.

To start the server you need to start the index.js file from the command line:

The Client-side Websocket Factory

To create a websocket on the browser, we already created an AngularJS factory in browser/js/app.js:

This uses the same set of modules we saw in the last post to create a persistent connection to the websocket server using the reconnect module and to turn the binary stream of that connection into a remove event emitter using duplex-emitter.

The server-side Websocket server

On the server side, we need to create the websocket server inside a new websocket directory, which will contain the websocket/list.js module:

This module handles a new client stream every time a client connects and builds a duplex emitter from that stream.

When the client sends events, the server reacts to these events, generally doing two things:

  1. Update the store: get the items from the store given the current list ID and update the items.
  2. Broadcast the changes to a room that contains all the users that are connected to this list.

Explaining the Room

Here, the room works like an echo chamber for users that are connected to the same list. Each user will get the events that are broadcasted into that room. Let’s then create this local rooms module that will do this for us (see websockets/rooms.js):

A room has a name (in our case, it will be the list ID) and you can add clients to that room. Once the client disconnects, the client gets removed from that room. A room can be broadcasted to, emitting the event to all of the clients in the room.

Wiring up the Websocket Server

Now we need to do some wiring of the websocket server. First, we must create the main websockets module that lets you install a websocket server into a server (websockets/index.js):

And then the glue code on the server, at the end of index.js:

The Client Controller

Now we need to create the list controller on the client side, which will control the to-do list screen (browser/js/controllers/list.js):

This controller does three main tasks:

  1. It initializes the connection state, telling the server which list ID is to be served. The server then sends a todos event containing all the todo items for that list.
  2. It reacts to user events and sends some relevant events to the server like the new, delete and update events.
  3. It reacts to server events and updates the scope model objects with it.

Booting it up

Once you have the new files in place, you can run browserify again:

And fire up the Node.js server:

You can then create a new to-do list and share that URL with other users (you can try that using a different browser window). You can then verify that all of the actions of one user are propagated to all of the connected users. When one user creates a new to-do item, this new item is propagated to all the other users that are connected to that list. When an item is removed by one client, that action happens on all of the other clients. When a client toggles the to-do item state, that state change propagates to all the connected clients. Take a look at the finished application:



Collaborative real-time applications are easy to build using Node.js. Using a remote event emitter on top of a websocket connection, you can express the logic of your application by reacting to events and by emitting events, making the application code expressive and succint.

You can also easily connect users by providing a room abstraction that makes it easy for your application code to broadcast events to all interested users.

Safari Books Online has the content you need

Check out these Node.js books available from Safari Books Online:

In just 24 sessions of one hour or less, Sams Teach Yourself Node.js in 24 Hours will help you master the Node.js platform and use it to build server-side applications with extraordinary speed and scalability. Using this text’s straightforward, step-by-step approach, you’ll move from basic installation, configuration, and programming all the way through real-time messaging between browser and server, testing and deployment. Every lesson and case-study application builds on what you’ve already learned, giving you a rock-solid foundation for real-world success!
Node.js is a powerful and popular new framework for writing scalable network programs using JavaScript. Professional Node.js begins with an overview of Node.js and then quickly dives into the code, core concepts, and APIs. In-depth coverage pares down the essentials to cover debugging, unit testing, and flow control so that you can start building and testing your own modules right away.
This book shows you how to transfer your JavaScript skills to server side programming. With simple examples and supporting code, Node Cookbook talks you through various server side scenarios often saving you time, effort, and trouble by demonstrating best practices and showing you how to avoid security faux pas.
Node Web Development gives you an excellent starting point straight into the heart of developing server side web applications with node. You will learn, through practical examples, how to use the HTTP Server and Client objects, the Connect and Express application frameworks, the algorithms for asynchronous execution, and use both SQL and MongoDB databases.

About the author

Pedro Teixeira is a geek, programmer, freelancer, and entrepreneur. Author of some Node.js modules, the Node Tuts screencast show, some books about Node.js and overall fervent proclaimer of the Node.js creed. He is also the Co-founder and Partner of The Node Firm, and the organizer of the Lisbon JavaScript Conference.

Tags: AngularJS, Bootstrap, Github, Javascript, jQuery, Node.js, WebSockets,

Comments are closed.