Node.js Introduction and Example Application

Printer-friendly versionSend by emailPDF version

Nodejs LogoNode.js is an amazing new technology, however, unless you’re specifically a seasoned JavaScript developer the process of becoming acquainted with it can quickly become overwhelming.  This article will provide an overview and an example to help you get up and running quickly, so even if you are not a seasoned JavaScript developer you can still benefit from this introduction article.  So without further ado let’s dig in.

What is Socket.IO? is an interesting project (it's a module for node.js) implementing WebSocket backend and frontend with support possible any browser you can imagine.  With that I will explain how to get started using it.Introducing Graphic

Installing Socket.IO and Express

If you don’t already have and/or expressjs node modules installed on your machine, now is a great time to do it, you can install them with npm:

 npm install –g express
 npm install
 node app

to test that your install was successful visit http://localhost:3000/

If you see the welcome to express text as illustrated above than you have successfully run the test express application.

To serve our static page we will use Express, a package which simplifies the whole server-side page send process. To include this package in a project you should create variable as illustrated below:

  var express = require('express'), app = express.createServer();

Next, we need to configure Express to serve the page from the repertory views with the Jade templating engine that we installed earlier.

Express uses a layout file by default, however, since we are only serving one page in this article we don’t  need it so instead we will disable it.

Express can also serve a static repertory to the client like a classic web server in that it has the capability to push a "public" folder which will contain our JavaScript, CSS, and image files.

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", { layout: false });
app.configure(function() {
   app.use(express.static(__dirname + '/public'));

We need to configure Express to serve a "home.jade" file, which we will create in a moment, and then set Express to listen for a specific port.

I will use port 3000 in this article but you can use whatever port you prefer.

app.get('/', function(req, res){

Chat App

For this article I will illustrate building a simple chat application.

 npm install

Like the other modules, we need to include it in our server.js file

 npm install socket.iovar io = require('').listen(app); creates a new socket that we will use to receive or send messages to the client.  Let’s start by initializing the connection:

io.sockets.on('connection', function (socket) {
   //our other events...

This function takes two arguments,

  • The first argument is the event in this case a connection
  • The second argument is the callback function in this case the socket object.

Code as illustrated in the above example allows us to create new events on the client and on the server with We will set the "pseudo" event and the "message" events next.

To set the pseudo and message events it’s simple, we just use the same syntax as above, however, this time with our socket object and not the "io.sockets" (with an “s”) object.  This allows us to communicate specifically with one client.

So inside our connection function, let’s add in the "pseudo" event code.

socket.on('setPseudo', function (data) {
   socket.set('pseudo', data);

The callback function takes one argument which is the data from the client and in our case it contains the pseudo. 'pseudo' is the name of this variable and the data is the value.

Now that we have defined the pseudo event we need to add in the code for the message event.  It will get the user’s pseudo, broadcast an array to all clients which contains the message we received as well as the user’s pseudo and log it into our console.

socket.on('message', function (message) {
   socket.get('pseudo', function (error, name) {
      var data = { 'message' : message, pseudo : name };
      socket.broadcast.emit('message', data);
      console.log("user " + name + " send this : " + message);

Since we are using we do not have to worry about handling client disconnections. When a client disconnects will no longer receive responses to “heartbeat” messages and will deactivate the session associated with the client. If it was just a temporary disconnection, the client will reconnect and continue with the session.

Create a "script.js" file inside the public folder.  We will store all of our application functions in script.js.

First we need to start the connection between the client and the server.  It will be stored in a variable, which we will use later to send or receive data. When the connection is not passed any arguments, it will automatically connect to the server which will serve the page.

 var socket = io.connect();

Next, let’s create some helper functions that we will need later. The first is a simple function to add a message to the screen with the user’s pseudo.

function addMessage(msg, pseudo) {
   $("#chatEntries").append('<div class="message"><p>' + pseudo + ' : ' + msg + '</p></div>');

This helper function uses the append function from jQuery to add a div at the end of the #chatEntries div.

Now we are going to write a function that we can call when we want to send a new message.

function sentMessage() {
   if ($('#messageInput').val() != "")
      socket.emit('message', $('#messageInput').val());
      addMessage($('#messageInput').val(), "Me", new Date().toISOString(), true);

In this function we verify that our textarea is not empty, then we send a packet named "message" to the server which contains the message text, we print it on the screen with our "addMessage" function, and finally we remove all the text from the textarea.

When the client opens the page, we need to set the user’s pseudo first. This function will send the pseudo to the server and show the textarea and the submit button.

function setPseudo() {
   if ($("#pseudoInput").val() != "")
      socket.emit('setPseudo', $("#pseudoInput").val());

Additionally, we hide the pseudo setting controls when it’s sent to the server.

Now just like we did on the server-side, we need to make sure we can receive incoming messages and this time we’ll print them on the screen. We’ll use the same syntax but this time we call the "addMessage"function.

socket.on('message', function(data) {
   addMessage(data['message'], data['pseudo']);

Just like with our server configuration, the packet that is sent to the client is an array containing the message and the pseudo. So we just call our "addMessage" function passing in the message and the pseudo, which we extract from the received data packet.

Finally we need to add the initialization function which is fired once the page is fully loaded.

$(function() {
   $("#pseudoSet").click(function() {setPseudo()});
   $("#submit").click(function() {sentMessage();});

There you have it.  We built a working chat application using node.js and

Enhanced by Zemanta

Leave a cooment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.