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 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 is 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 lets move towards actual implementation of 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.

    Note: I’m using windows machine
  3. Create a package.json file which is the manifest file that describes our project.

    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.

    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.

    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.

    put above code in style.css and save the file.
  7. Now create index.js file that will setup our application on server.

    Above code translates into the following:

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

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

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

    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 name of user to display “xyz is typing” message to the user.
    • Register the event chatMessage which listens 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 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 following command.

    The above command will result in below screen

  9. Now go to your favourite 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 useful. 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.

Special thanks to all readers and followers..!!

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

  1. pranava

    Hello, everything is fine while i am doing this but, my message after typing in the placeholder is not displaying after clicking the send button. Can you please me help me with this problem? TIA

    Reply
    1. Sarang Raotole

      Hi Pranava, please check whether external scripts references i.e. socket.io etc are downloaded appropriately and references to internal scripts i.e. chat,js etc are been pointed to appropriate path.

      Reply
  2. Bhomihar AmitKumar

    Thank for your code,its really helpful,but i want to know that how can i use this chat application in multiple computers….

    Reply
  3. suriya

    dude… is just bravo man…!!!!!
    i need to clarify few thing with you.. could u pls connect with me ? through [email protected]

    Reply
    1. Sandip Salunke

      Hi Suriya,

      You can contact me on [email protected]

      Reply
  4. Srinivas

    Hello Its very nice
    It is working only localhost
    I want My own IP
    for that WHat I need to do Please let me know

    Reply
      1. Vinod Kumar

        must say its a very nice app and i am trying to add my ip to this application but i am not able to locate the http://localhost/chatApplication command in app modules.i am attaching my email id with this text.please help me to solve this
        Thanks
        [email protected]

        Reply
    1. Sandip Salunke

      Hi Anshul

      Thanks for using this tutorial, I believe you are doing well.

      Regarding you requirement, in order to show the list of connected/online users you need to assign an unique ID’s to each user and on connect event you need to emmit an event to add user in the list.

      I hope this will help you, please feel free if you need further assistance.

      Regards
      Sandip S.

      Reply
    1. Sandip Salunke

      Thank you Minakshi for using this tutorial.

      Minakshi, please do refere your friends to use this tutorial.

      Reply
  5. Vipul Malhotra

    I would like to implement this in my application with one more feature that the chat should be saved in DB so that it can be reviewed later.
    Now I would want to DB insertion to take place asynchronously in the background without delaying the response time in this feature.
    Could you please guide a bit on how to achieve this.

    Reply
    1. Sandip Salunke

      Hi Vipul,

      Thanks for using tutorial, I believe you are doing well.

      Regarding your requirement, in order to perform database operations you need to create a REST APIs in any of the backend technology like PHP or .Net and make a ajax calls.

      I hope this will help you, in case you need further help feel free to post here.

      Regards
      Sandio S.

      Reply
  6. Sourav

    I am new in node js .Its really awesome tutorial and helpful for beginer like me.Great job .

    I have used django for my webportal and i want to build chat functionality with user to admin. Basically one(user) to one (Admin).So Please can you help to build to it or can you give me some github project or any other source.

    Thanks in advance !!!!!!!

    Reply
    1. Sandip Salunke

      You need to assign a unique id to each user and establish one to one connection anongst them.

      Actually this is the next assignment you have to try to get better understanding.

      Thanks!!

      Reply
  7. Shravan

    Awesome tutorial…!!!
    Could you specify the directory structure of project and want to clarify few doubts that why didn’t you install node.js.
    Do we need to put _dirname or it takes automatically.
    When index.js is called.

    Reply
  8. architsisodia

    hi how can i use it from remote computer ..I mean i want to use from my friend system… i have given my system ip …but its not working that whole view is coming but chat not working…

    Reply
  9. ofobrukweta

    please do you have videos on this described steps above and other videos on exploring the node.js more

    Reply
  10. Nayana

    Thank you so much!!!!!
    I have tried the live chat app last 4 hours but its not working, using this tutorial it just done with few mints.
    It’s Help me a lot.

    Reply
  11. Vinoth

    Wow nice it is..
    but i want to show a name in chat interface with with login.
    is it possible with this code

    Reply
  12. sudip

    hi Mr. sandip,
    i could not able to run the application.
    after creating package jason , I installed http , socket.io , express and path through git bash terminal and initiated “npm install “command to generate node module in that directory.
    then i created index.html,index.js,chat.js and style.css
    and put correct directory at res.sendFile(path.join(__dirname, ‘../iochat’, ‘index.html’));
    When i went to run the application with node index.js command, i found that blank server localhost:3000 is appeared before without any content.
    Kindly help me out.

    Reply
  13. sudip

    package jason file is as follows

    {
    “name”: “iochat”,
    “version”: “1.0.0”,
    “description”: “simple io chat”,
    “main”: “index.js”,
    “dependencies”: {
    “express”: “^4.14.0”,
    “socket.io”: “^1.7.1”,
    “http”: “^0.0.0”,
    “path”: “^0.12.7”
    },
    “devDependencies”: {},
    “scripts”: {
    “test”: “echo \”Error: no test specified\” && exit 1″,
    “start”: “node server.js”
    },
    “author”: “sudip”,
    “license”: “ISC”
    }

    kindly help me

    Reply
  14. Anoop

    App is working okay for me , but if i want to change index.html into index.php . The reason of changing is that, I wanna use session value in users name ,, so user can chat by there name rather than randon id .

    Thanks

    Reply
  15. Sreejith BS

    Hi,

    I had a small doubt. In the chat window can we place a button/menu for where user can select the option he want.

    Reply

Leave A Comment

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