Skip to content

Part 2: Building the server with Node.js and Socket.io

Sergi Almar edited this page Nov 20, 2013 · 8 revisions

Creating the Node.js project

In order to have the skeleton of the project, we'll rely on express.js (the sinatra-like framework). Install express globally with the following command:

sudo npm install –g express

Now let's create an express based app called mobos-chat

express mobos-chat

The following structure will be created

   
create : mobos-chat
   create : mobos-chat/package.json
   create : mobos-chat/app.js
   create : mobos-chat/public
   create : mobos-chat/views
   create : mobos-chat/views/layout.jade
   create : mobos-chat/views/index.jade
   create : mobos-chat/public/images
   create : mobos-chat/routes
   create : mobos-chat/routes/index.js
   create : mobos-chat/routes/user.js
   create : mobos-chat/public/stylesheets
   create : mobos-chat/public/stylesheets/style.css
   create : mobos-chat/public/javascripts

Notice that a file called package.json containing the dependencies has been created. Execute npm install to add them to the project (check that the node_modules folder is created and contains the dependencies).

The app.js is the entry point to our application, it imports the required modules, defines some routings and creates the http server. Open and take a look at it. This should be enough to start our application.

Execute node app or npm start to start the app. Check that typing 'http://localhost:3000/' in your browser gives you the welcome page.

Adding Socket.io

By now, you should be familiar with packages.json. In order to add the Socket.io support we need to define it as a dependency in such file, open it and add: "socket.io" : "~0.9.16"

Let's now create a module which will encapsulate the socket.io logic. Create a file called socket.js inside the routes folder.

This module will use the socket.io dependency that we have already defined. Import it in the module

var socketio = require('http');

The modules contain logic private to the module itself, they encapsulate logic, but remember that they can also expose it using the CommonJS convention (with the exports variable). Let's expose a function called initializeso we can initialize it from another module:

exports.initialize = function(server) {
    io = socketio.listen(server);
}

We have added a server parameter (this will be the http server already created in the app.js file), as

Clone this wiki locally