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
- Let’s create a folder called chat-application to hold our application files.
- 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
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
All set, 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
- Initialize socket Io using var socket = io();
- Now go to your favorite web browser and open link(localhost:3000) in two different windows.
- Hurrey…!!! we have successfully created a chat application and its working like a charm.
Quick References
I Hope you have enjoyed this tutorial and find it easy to learn, implement and use. 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..!!
This is one of the best tutorial in world history. I love it. keep it up Sir.
This is the best comment we ever got. 🙂
There are many people facing issues with working on this application. let me help these people and the one who are going to face the similar problems.
When you face issue not able to send message, message does not appear, please make sure versions of all your node modules are as per the package.json file in this tutorial. If you have higher versions then you have to make respective change to use those node modules. Or you can install the exact same version as mentioned in package.json.
If you are still not able to make it work, you can put comment here so that Myself or anyone here can help you to fix it. Make sure you pull in console logs of client(browser) as well as serve to help understand the problem.
If you want to reach out to me, please connect via
Email: [email protected] (CC: [email protected])
Mb.: 8796907719
Hi,
I want this type of comment and reply functionality using node js and mysql.
Sandip very nice and helpful and very simply explain it is.
Thanks!
Hi All,
I got request for advance version of chat application. I have written a separate article for this, you can read it http://94.143.139.145/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
Nice article….!!!
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.
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.
hello I got error…. when I enter text in textbox and hit enter then nothing happens
Nice Tutorial!!!!!!!!
Hi,
I want comment,reply and favourite like module using node js and mysql
how to create a group chat. i mean create a room for particular users.. kindly help me. i am the beginner of node
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?
hi, it’s very nice tutorial but while i am doing it after typing the message when I click on send button it does not appears. could u please help me on that
Sir,
First of all, thank you for this great tutorial. I am facing the same problem some people faced here. As soon as i enter a message, the connection breaks, the page refreshes and a new connection is established. Can you please help me?
email: [email protected]
Hi Phanindra,
Yes, you are right, the application is not working because when you did npm install socket.io, it has installed the version 2.0.3.
But in the clint.js you are using 1.x. To make it working you need to update an entry within the client.js.
New URL: https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js
Not working for me as well.
HI i’m newbie to node js even though this tutorial help me do step by step even i made progress around it ……
but i can’t able to see sent message at top tried debugging it by ensuring socket.io,client.js are located in proper directory …… but could not able to made progress could please help me in solving it
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
How can i include emoticons to the chat application
Please follow below steps
1. Create a set of emoticon images and their short-codes.
2. Create a section where you can display all emoticons and on click of them you have to add its short-code in raw message.
3. When reading and displaying the chat message you have to replace all short-code with their respective emoji icon/image.
Its bit complex, but yes can be done smartly.
hi,
if i want make it as normal chat(conversation panel),i mean user to user.what i have to do.how to host this application.
how can i setup with php index.html
Great guide. Works flawless.
How can i set this up using ejs for the view instead of html?
simple as converting the HTML file to your view template file.
Simply great…
Thank you so much for this tutorial. Can I use your code for a school project ?
Sure, its open source. You can use it. For advance version of it please do check http://94.143.139.145/node-js/chatbox-a-peer-to-peer-chat-application/
I am sure you will like it.
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.
I get a error message no such file or directory index.html…..
awsome..common chat room..really great..!
nce one
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
instead index.html pass index.php the app will work fine…
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
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.
Wow nice it is..
but i want to show a name in chat interface with with login.
is it possible with this code
Yes, its possible. You can use the username storred in your user session instead of generating a random userID.
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.
Awesome tutorial. Thanks a lot.
Nice post its good example for begine
never the less awesome tutorial
please do you have videos on this described steps above and other videos on exploring the node.js more
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…
Very helpful, thanks
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.
nice tutorial
Nice work
Thank Working perfectly
Thanks Sonali!!!
Hey! Nice tut man. One that actually works! How would I make this live? I guess Im asking how would I Put this on a www website?
You can deploy your code to server.
Thanks!!
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 !!!!!!!
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!!
thank you buddy
You are well come Gaurav, please do refer your friends to use this tutorial.
Awesome
Thanks buddy
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.
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.
nice post
Thank you Minakshi for using this tutorial.
Minakshi, please do refere your friends to use this tutorial.
how to show online user in friends list by using soket io
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.
You have to do following things
– Maintain the list of Online users and show that where ever you want (May be right-bottom corner)
– As soon as any client (user) joins you need to emit an event say ‘newUserJoined’ and listen that to add user to the list of online users.
– Similarly, as soon as any client (user) leaves, you have to emit an event say ‘userLeft’ and listen that to remove user from the list of online users.
I hope this may help.
An awesome tutorial. Thanks.
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
Hi SRINIVAS,
Thanks for your interest and review…!!
It’s a web based application and if you want to execute it using your IP address in browser then you can put your IP address instead of localhost and access the same from remote machine.
Ex.
I’m using
http://localhost/chatApplication
then you can use
http://172.16.0.1/chatApplication
I hope this may help you and makes sense.
Regards
Sandip
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]
Thanks this was very helpful1!!!
nice demo
dude… is just bravo man…!!!!!
i need to clarify few thing with you.. could u pls connect with me ? through [email protected]
Please ask your question here. Some one might be able to answer your question or if i get a chance i will answer the question.
Hi Suriya,
You can contact me on [email protected]
Very Nice Demo. Worth reference to start with node chat sample app.
Thank for your code,its really helpful,but i want to know that how can i use this chat application in multiple computers….
Its a web based demo, you can use this on N number of computers.
nice, its working good
Thanks for using this tutorial, please do share with your friends.
MUITO OBRIGADO
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
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.
im also having the same problem
I am also facing the same issue.
Sandip Salunke can you please help me regarding this??
Awesome Tutorial
Nice Post.
It’s helps me a lot 😉
cool , thanks
I tried to do exactly what was told in the tutorial but as soon as i enter a message, the page refreshes and the connection breaks and then reconnects. Can you help me, Please!
email: [email protected]