Build a Node.js-powered Chatroom Web App: Node, MongoDB and Socket

Originally published at: http://www.sitepoint.com/build-node-js-powered-chatroom-web-app-node-mongodb-socket/

This Node.js tutorial series will help you build a Node.js-powered real-time chatroom web app fully deployed in the cloud. In this series, you will learn how to setup Node.js on your Windows machine (or just learn the concepts if you’re on Mac), how to develop a web frontend with Express, how to deploy a node express apps to Azure, how to use Socket.IO to add a real-time layer, and how to deploy it all together.

The tutorial will use the optional Visual Studio and the Node.js Tools for Visual Studio plug-in as a development environment—I have provided links to free downloads of both tools. This is a beginner- to intermediate-level article –you’re expected to know HTML5 and JavaScript.

Part 1 – Introduction to Node.js

Part 2 – Welcome to Express with Node.js and Azure

Part 3 – Building a Backend with Node, Mongo and Socket.IO

Part 4 – Building a Chatroom UI with Bootstrap

Part 5 – Connecting the Chatroom with WebSockets

Part 6 – The Finale and Debugging Remote Node Apps

Part 3 – Building a Chatroom Backend with Node.js, Socket.IO and Mongo

Welcome to Part 2 of the hands-on Node.js tutorial series: Build a Node.js-powered chatroom web app. In this installment, I will show you how to use your existing express-based Node.js app to create a chatroom backend with WebSocket support.

What are WebSockets? What is Socket.IO?

WebSocket is a protocol designed to allow web applications to create a full-duplex channel over TCP (i.e. to have bi-directional communication) between the web browser and a web server. It is fully compatible with HTTP and uses TCP port number 80. WebSocket has allowed web applications to become real-time and support advanced interactions between the client and the server. It is supported by several browsers including Internet Explorer, Google Chrome, Firefox, Safari and Opera.

Socket.IO is a JavaScript library and Node.js module that allows you to create real-time bidirectional event-based communication apps simply and quickly. It simplifies the process of using WebSockets significantly. We will be using Socket.IO v1.0 to make our chatroom app.

Adding Socket.IO to package.json

Package.json is a file that holds various metadata relevant to the project, including its dependencies. npm can use this file to download modules required by the project. Take a look at this interactive explanation of package.json and what it can contain.

Let’s add Socket.IO to the project as a dependency. There are two ways to do that.

  1. If you have been following the tutorial series and have a project in Visual Studio setup, right-click on the npm part of the project and select “Install New npm Packages…”

Once the window has opened, search for “socket.io”, select the top result and check the “Add to package.json” checkbox. Click the “Install Package” button. This will install Socket.IO into your project and add it to the package.json file.

Adding Sockets.IO to npm

package.json

{
  "name": "NodeChatroom",
  "version": "0.0.0",
  "description": "NodeChatroom",
  "main": "app.js",
  "author": {
    "name": "Rami Sayar",
    "email": ""
  },
  "dependencies": {
    "express": "3.4.4",
    "jade": "*",
    "socket.io": "^1.0.6",
    "stylus": "*"
  }
}
  1. If you’re on OS X or Linux, you can achieve the same action as the above by running the following command in the root of your project folder.
npm install --save socket.io

Adding Socket.IO to app.js

The next step is to add Socket.IO to app.js. You can achieve this by replacing the following code.

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

To be replaced with:

var serve = http.createServer(app);
var io = require('socket.io')(serve);

serve.listen(app.get('port'), **function** () {
    console.log('Express server listening on port ' + app.get('port'));
});

This will capture the HTTP server in a variable called serve and pass that HTTP server so that the Socket.IO module can attach to it. The last code block takes the serve variable and executes the listen function which starts the HTTP server.

Logging a User Joining and Leaving

Ideally, we want to log a user joining the chatroom. The following code accomplishes that by hooking a callback function to be executed on every single connection event via WebSocket to our HTTP server. In the callback function, we call console.log to log that a user connected. We can add this code after we call serve.listen.

io.on('connection', function (socket) {
    console.log('a user connected');
});

To do the same for when a user disconnects, we have to hook up the disconnect event for each socket. Add the following code inside after the console log of the previous code block.

socket.on('disconnect', function () {
        console.log('user disconnected');
    });

Finally, the code will look like this:

io.on('connection', function (socket) {
    console.log('a user connected');
    socket.on('disconnect', function () {
        console.log('user disconnected');
    });
});

Broadcasting a Message Received on the Chat Channel

Socket.IO gives us a function called emit to send events.

Any message received on the chat channel will be broadcast to all the other connections on this socket by calling emit with the broadcast flag in the callback.

socket.on('chat', function (msg) {
    socket.broadcast.emit('chat', msg);
});

Finally, the code will look like this:

io.on('connection', function (socket) {
    console.log('a user connected');
    socket.on('disconnect', **function** () {
        console.log('user disconnected');
    });

    socket.on('chat', function (msg) {
        socket.broadcast.emit('chat', msg);
    });
});

Saving Messages to a NoSQL Database

The chatroom should save chat messages to a simple data store. Normally, there are two ways to save to a database in Node; you can use a database-specific driver or you can use an ORM. In this tutorial, I will show you how to save the messages to MongoDB. Of course, you can use any other database you like, including SQL databases like PostgreSQL or MySQL.

You should make sure you have a MongoDB to connect to. You can use a third-party service to host your MongoDB such as MongoHQ or MongoLab. Take a look at this tutorial to see how you can create a MongoDB using the MongoLab Add-On in Azure. You can stop reading when you get to the section “Create the App”, just make sure to save the MONGOLAB_URI somewhere you can access easily later.

Once you have created a MongoDB and you have the MONGOLAB_URI for the database – Under Connection info that you have copied to your clipboard – you will want to ensure that the URI is available to the application. It is not best practice to add sensitive information such as this URI into your code or into a configuration file in your source code management tool. You can add the value to the Connection Strings list in the Configuration menu of your Azure Web application (such as in the tutorial you used) or you can add it to the App Setting list (with Name CUSTOMCONNSTR_MONGOLAB_URI). On your local machine, you can add it to the environment variables with the name CUSTOMCONNSTR_MONGOLAB_URI and value of the URI.

Continue reading this article on SitePoint
1 Like

When I create a nodejs azure express 4 template and add socket.io, I get an error while deploying the app to azure.

Error 195: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

Can you help me out, for other readers as well?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.