Create simple chat application using Node.JS, Express.JS and Socket.IO

Introduction

This article is all about creating a simple chatting application using Node.JS, Express.JS, and Socket.IO. There are many different ways to implement this using traditional languages like PHP, .Net, SignalR etc. There are different libraries available in the market like chatJS, jQuery+AJAX. We can also use third-party libraries but they might be paid services. 

Here we are going to implement our own chat application which completely depends on open source technologies and is extremely easy to implement. So before going for the actual implementation lets have a look basic components of this application.

Node.js

Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript. Node.js provides an event-driven architecture and a non-blocking I/O API that optimizes an application’s throughput and scalability. These technologies are commonly used for real-time web applications. Node.js is also called as server side javascript which supports non-blocking event driven IO operations.

Express.js

Express is a framework of Node.js that allows you to use several very useful and powerful features helps you organize your application’s routing and use any templating solution with minimal effort. It also allows for much better organization of your code. Express provides features by extending core functions of Node.js.

Socket.IO

Socket.IO is a JavaScript library for realtime web applications. It enables realtime, bi-directional communication between web clients and server. It has two parts: a client-side library that runs in the browser, and a server-side library for node.js. Both components have a nearly identical API. Like node.js, it is event-driven. Socket.IO provides the ability to implement real-time analytics, binary streaming, instant messaging, and document collaboration.

Getting Started

Now, let’s move towards actual implementation of the application. Here I’m assuming that you have installed Node.js and Express.js successfully and ready to move on. If you have not installed the same yet then do follow the installation steps for both at given link.

Quick steps

  1. Let’s create a folder called chat-application to hold our application files.
  2. Now open NodeJS command prompt/terminal and navigate to your application directory i.e. chat-application.
    cd Desktop\projects\chat-application
    

    Note: I’m using windows machine

  3. Create a package.json file which is the manifest file that describes our project.
    {
     "name": "socket-chat-example",
     "version": "0.0.1",
     "description": "my first socket.io app",
     "dependencies": {}
    }
    

    put above code in package.json and save the file.

  4. Install Express, HTTP, socket.io and path npm modules in your working directory i.e. chat-application.
    npm install --save [email protected]
    npm install http
    npm install socket.io
    npm install path
    

    The above command will result in below screen, You can see all the default packages of express are installed successfully.

  5. Now create a HTML file i.e. index.html which is used to serve the chat window in browser.

    <!doctype html>
      <html>
       <head>
        <title>Chat Application</title>
        <link rel='stylesheet' href='style.css' type='text/css'/>
        <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
        <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
        <script src="chat.js"></script>
      </head>
      <body> 
        <ul id="messages"></ul>
        <span id="notifyUser"></span>
        <form id="form" action="" onsubmit="return submitfunction();" > 
          <input type="hidden" id="user" value="" /><input id="m" autocomplete="off" onkeyup="notifyTyping();" placeholder="Type yor message here.." /><input type="submit" id="button" value="Send"/> 
        </form>
      </body>
    </html>

    Here <ul> is used to list the chant messages, <span id=”notifyUser”> is used to notify user that another user is typing the message and the <form> with input box and button is used to send chat messages. put above code in index.html and save the file.

  6. Now create a css file i.e. style.css to design the chat window.
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font: 13px Helvetica, Arial; }
    form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
    form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
    form #button { color:#FFF; background: #2D9F0B; border: none; padding: 10px;  width: 9%; }
    #messages { list-style-type: none; margin: 0; padding: 0; }
    #messages li { padding: 5px 10px; }
    #messages li:nth-child(odd) { background: #eee; }
    #notifyUser { position: fixed; bottom: 42px; width: 100%; }

    put above code in style.css and save the file.

  7. Now create index.js file that will setup our application on server.
    var app = require('express')();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    var path = require('path');
    
    // Initialize appication with route / (that means root of the application)
    app.get('/', function(req, res){
      var express=require('express');
      app.use(express.static(path.join(__dirname)));
      res.sendFile(path.join(__dirname, '../chat-application', 'index.html'));
    });
    
    // Register events on socket connection
    io.on('connection', function(socket){ 
      socket.on('chatMessage', function(from, msg){
        io.emit('chatMessage', from, msg);
      });
      socket.on('notifyUser', function(user){
        io.emit('notifyUser', user);
      });
    });
    
    // Listen application request on port 3000
    http.listen(3000, function(){
      console.log('listening on *:3000');
    });

    Above code translates into the following:

    • First block includes all the modules we are needing in our application
    • Second block initializes out an application on the server
    • Third block registers events on a socket connection
    • Fourth block make the http server listen application requests on port 3000

    The events chatMessage and notifyUser are used to listen to the requests from events emitted by client-side scripts. and based on that server emits the respective events which are then listening by client-side scripts.

  8. Now create file for client side script i.e. chat.js

    var socket = io(); 
    function submitfunction(){
      var from = $('#user').val();
      var message = $('#m').val();
      if(message != '') {
      socket.emit('chatMessage', from, message);
    }
    $('#m').val('').focus();
      return false;
    }
    
    function notifyTyping() { 
      var user = $('#user').val();
      socket.emit('notifyUser', user);
    }
    
    socket.on('chatMessage', function(from, msg){
      var me = $('#user').val();
      var color = (from == me) ? 'green' : '#009afd';
      var from = (from == me) ? 'Me' : from;
      $('#messages').append('<li><b style="color:' + color + '">' + from + '</b>: ' + msg + '</li>');
    });
    
    socket.on('notifyUser', function(user){
      var me = $('#user').val();
      if(user != me) {
        $('#notifyUser').text(user + ' is typing ...');
      }
      setTimeout(function(){ $('#notifyUser').text(''); }, 10000);;
    });
    
    $(document).ready(function(){
      var name = makeid();
      $('#user').val(name);
      socket.emit('chatMessage', 'System', '<b>' + name + '</b> has joined the discussion');
    });
    
    function makeid() {
      var text = "";
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    
      for( var i=0; i < 5; i++ ) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
      }
      return text;
    }

    Above code translates into the following:

    • Initialize socket Io using var socket = io();
      On form submit get the value of input box and emit the chatMessage event along with text message.
    • On keypress event of input box emit the notifyUser along with the name of user to display “xyz is typing” message to the user.
    • Register the event chatMessage which listens to the request from server when user send chat message. Append chat message to the list (<ul>)
    • Register the event notifyUser which listens the request from server when user start typing chat message. Display “xyz is typing” message to the user.
    • On document.ready function create unique user name and emit chatMessage event to send a welcome message.
    • Function makeid() is used to generate unique user name to be display.

    We have done with all the coding stuff, now go to your node command prompt and run the application with the following command.

    node index.js

    The above command will result in below screen

  9. Now go to your favorite web browser and open link(localhost:3000) in two different windows.
  10. Hurrey…!!! we have successfully created a chat application and its working like a charm.

Quick References

  1. http://socket.io/
  2. https://nodejs.org
  3. http://expressjs.com/

I Hope you have enjoyed this tutorial and find it easy to learn, implement and use. I have tried my best to group everything inside a single document which is needed to implement a simple chat application. I have written this tutorial based on my experience and knowledge. There might be some glitches present in this tutorial, please bear with me and let me know if you find any problem. Any suggestions/improvements in this tutorial are welcome.

I have written a new article with an advanced feature of peer to peer chat application.

Special thanks to all readers and followers..!!

83 Comments Create simple chat application using Node.JS, Express.JS and Socket.IO

  1. Prashant Chamoli

    How will others users be able to use this application if I publish it on GitHub?Will they also have to install all npm modules?

    Reply
  2. Mayank

    For all those who are wondering, why this program is not running.. you should have to upgrade ‘socket.io-1.2.0.js’ to the latest one and it will definitely work.
    Thank you.

    Reply
  3. Sandip Salunke

    Hi All,

    There are few error that people are facing, please follow up with the below steps to resolve those errors.

    1. When user types a message and hit send button, page gets reloaded.
    >> Please try checking console for any error. This is caused because jquery reference is not able to locate the jquery library referenced in index.html. Please update this reference to the latest jquery version.

    2. When user sends a message it just vanishes and not actually sent to any other user.
    >> The reason behind this error is, you installed the latest version of socket.io npm package and your reference to its client version is still pointing to some older version. Try to change its reference in index.html to the new version.

    I hope these are the only commonly faced issues with this tutorial and this will help.

    Reply
  4. Sandip Salunke

    Hi All,
    I got request for advance version of chat application. I have written a separate article for this, you can read it https://javabeginnerstutorial.com/node-js/chatbox-a-peer-to-peer-chat-application/

    What’s new there?

    1. Peer to peer chat.
    2. List of online users.
    3. Chat notification with the count of new messages.
    4. Notification sound when a new message comes in from selected and non-selected users.
    5. Assign a user-defined name to the user instead of random ID.
    6. Display username (My name) at top of online users list and as document title.
    7. Improved User experience by changing some CSS properties. Improved chatBox messages UI.

    I hope you will enjoy and find it helpful.

    Thanks!
    Sandip Salunke

    Reply

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.