The two most amazing features of Node.js – non-blocking I/O and event-driven – the best backend technology for building fast and scalable Real-time applications. The speed and scalability of Node.js made it the right technology for data-intensive, real-time applications. App developers widely make use of Node.js when they want to use JavaScript on client-side and server-side. The very name “Node.js” indicates that it helps building distributed apps with numerous nodes. Scalability is an inherent aspect of the Node.js platform and it facilitates both types of scaling – horizontal and vertical. For horizontal scaling of the app nodes are to be added to the existing ones and for vertical scaling resources are to be added.
The 5 outstanding reasons for choosing Node.js as the programming language for building Real-time Applicatio
1. Scalability
Node.js is a superb technology that ensures non-blocking functionality. The asynchronous I/O method of Node.js enables the app builders to create real-time applications that are capable of smoothly managing high request volumes. Node.js is the best platform to build Real-time sports event apps that require scalability and speed. Since Node.js runs on the V8 engine, it is the most ideal technology for developing applications for large enterprises. Node.js enables app developers to build real-time apps that can handle more numbers of incoming connections.
2. Quick response
The event loop model of Node.js single-threaded. It can handle more number of concurrent requests from users without going for making additional threads. This aspect of Node.js helps reduce response time considerably.
3. Single Codebase
Node.js enables app developers to deploy and execute codes very easily and very quickly. Since there is no need of conversion, it enables faster transmission of data between client and server. It simplifies the process of sending data from server to client.
4. Data Streaming
Node.js is the best option for creating OTT streaming apps. Instead of transmitting data in a single big package, the data is sent to the front end in small chunks. This will make loading of data packages easier.
5. Facilitates further improvement
Node.js platform is very easily extensible. It offers immense possibilities for improvement. The coder who uses Node.js for writing a backend need not modulate the syntax differences since it uses NoSQL queries to run through databases. There won’t be any data-conversion issue while running the data and this a great advantage while creating real-time web apps. Node.js has built-in APIs which can be used for making HTTP and TCP servers.
Socket.io
WebSocket enables app builders to create highly user-friendly real-time applications. The advantage of the WebSocket communication protocol is that without waiting for request from the client the server can send him the data. WebSocket API is used while building the applications. But, for building an application using the Node.js platform, JavaScript and Node.js library Socket.io is used instead of WebSocket API. This will make the process simpler.
Creation of Real-time application using Node.js – An Example
Now, let us see how a simple chat-room is made using Node.js.
This chat-room will be having the three features listed below:
1. User can change the username
2. Send messages
3. See whether another user is typing message currently
Building up the app environment
As the first step of the app creation, we need to make a new directory for the particular application. Subsequently, the npm init is to be run so as to set up the package file.
In this example for creation of Real-time Application using node.js, we use the following tools:
1. the Express
2. ejs – a widely used JS template engine
3. Socket.io
4. Nodemon – a package to restart the server whenever changes are made to the application code. This package is used only for development purpose and when we use Nodemon we need not manually stop and start the server every time we make a change.
The command given below is used for installing express, ejs and Socket.io.
npm install express ejs socket.io –save
Next, install Nodemon using the following command.
npm install nodemon --save-dev
In the next step, we will be starting the application with Nodemon. We have to add the following start script to the package.json file.
"scripts": {
"start": "nodemon app.js",
},
Now we will start the application by running the following command on the command-line.
npm run start
In case we don’t have a code file, the above step may fail but, you need not worry.
Setting up the application structure
Now we have to build up the structure of the application. A few directories and a file called app.js areto be created.
|--app.js
|--views
|--node_modules
|--package.json
|--public
|--css
|--js
Now we have the clear structure and let us go through each item in the above structure:
app.js – this file will be used to host server-side code
views – the folder that contains the views (ejs)
node modules – our dependencies are installed here
package.json – the npm configuration file
public – directory for storing various assets like css files, javascript files and images.
Building the Server
As the first step, the app.js file is opened and paste the code given below so as to get express running.
const
express
=
require
(
'express'
)
const
socketio
=
require
(
'socket.io'
)
const
app
=
express
()
app
.
set
(
'view engine'
,
'ejs'
)
app
.
use
(
express
.
static
(
'public'
))
app
.
get
(
'/'
, (
req
,
res
)=> {
res
.
render
(
'index'
)
})
const
server
=
app
.
listen
(
process
.
env
.
PORT
||
3000
, () => {
console
.
log
(
"server is running"
)
})
Since express is configured, we can go for sockets.io initialization using ejs as template system. At the end of the app.js file, add the code given below:
//initialize socket for the server
const
io
=
socketio
(
server
)
io
.
on
(
'connection'
,
socket
=> {
console
.
log
(
"New user connected"
)
})
After initializing socket.io from our server connection we set up the even using io.on (). It gets triggered when a new connection to the server is established.
Now you can receive new socket connections just by running the server with npm start.
Building your front-end
Now we want to create a template into the views folder. As the first step, create an index.ejs file and paste the code given below.
<!DOCTYPE html>
<
head
>
<
title
>Simple realtime chatroom</
title
>
<
link
rel
=
"stylesheet"
href
=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
>
</
head
>
<
body
>
<
div
class
=
"container"
>
<
div
class
=
"title"
>
<
h3
>Realtime Chat Room</
h3
>
</
div
>
<
div
class
=
"card"
>
<
div
class
=
"card-header"
>Anonymous</
div
>
<
div
class
=
"card-body"
>
<
div
class
=
"input-group"
>
<
input
type
=
"text"
class
=
"form-control"
id
=
"username"
placeholder
=
"Change your username"
>
<
div
class
=
"input-group-append"
>
<
button
class
=
"btn btn-warning"
type
=
"button"
id
=
"usernameBtn"
>Change</
button
>
</
div
>
</
div
>
</
div
>
<
div
class
=
"message-box"
>
<
ul
class
=
"list-group list-group-flush"
id
=
"message-list"
></
ul
>
<
div
class
=
"info"
></
div
>
</
div
>
<div class="card-footer">
<
div
class
=
"input-group"
>
<
input
type
=
"text"
class
=
"form-control"
id
=
"message"
placeholder
=
"Send new message"
>
<
div
class
=
"input-group-append"
>
<
button
class
=
"btn btn-success"
type
=
"button"
id
=
"messageBtn"
>Send</
button
>
</
div
>
</
div
>
</
div
>
</
div
>
</
div
>
<
script
src
=
"https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"
></
script
>
<
script
src
=
"/js/chatroom.js"
></
script
>
</
body
>
</
html
>
Script of the client-side socket.io library and the custom JavaScript file that we will be using are included. Note how they are included.
<
script
src
=
"https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"
></
script
>
<
script
src
=
"/js/chatroom.js"
></
script
>
When you want to send a new message you can use the button with ID messageBtn and when you want to submit new username, use the button with ID usernameBtn. IDs for username and message inputs are username and message respectively. All user messages appear inside the unordered list with the ID message-list.
The next step is connecting the front-end to the server. Anew javascript file with name chatroom.js must be created in the js folder of the public directory. Inside the javascript file, connection to socket must be made from the front-end.
(
function
connect
(){
let
socket
=
io
.
connect
(
'http://localhost:3000'
)
})()
Your app is ready and is working!
Changing your username
For every new connection first we give a default username and afterwards the user can change the same. When there is a change username event occurs from front-end, we set up the back-end to change the username. For addition of the new code you may go back to the server-side code (app.js) and edit your connection event.
io
.
on
(
'connection'
,
socket
=> {
console
.
log
(
"New user connected"
)
socket
.
username
=
"Anonymous"
socket
.
on
(
'change_username'
,
data
=> {
socket
.
username
=
data
.
username
})
})
Next step is adjusting the front-end after which if we press the change – username button it will emit an event to the server with the name change username.
Now we want to add an event listener to the usernameBtn inside charoom.js. As a result, when the button is clicked a change _ username event will be emitted.
(
function
connect
(){
let
socket
=
io
.
connect
(
'http://localhost:3000'
)
let
username
=
document.
querySelector
(
'#username'
)
let
usernameBtn
=
document.
querySelector
(
'#usernameBtn'
)
let
curUsername
=
document.
querySelector
(
'.card-header'
)
usernameBtn
.
addEventListener
(
'click'
,
e
=> {
console
.
log
(
username
.
value
)
socket
.
emit
(
'change_username'
, {
username
:
username
.
value
})
curUsername
.
textContent
=
username
.
value
username
.
value
=
''
})
})()
Now if you submit the new username after re-loading the web page you will find the current username replaced with the new username.
Message sending
Now we want to add the ‘sending message’ feature. Instead of the front-end emitting a message and the server receiving the same, in this case, the new message_event emitted by front-end will be sent to all the clients who are connected so that all of them can print the message. As the first step we set up the front-end to emit a new_message event on submission of a new message. Configure the client-side also to receive new messages sent by users from the server. Also the application must start listening the receive_message events on the front-end and show the message on the web page. We can use the following code to complete both the above tasks. It goes inside the previous connect function in chatroom.js.
let
message
=
document.
querySelector
(
'#message'
)
let
messageBtn
=
document.
querySelector
(
'#messageBtn'
)
let
messageList
=
document.
querySelector
(
'#message-list'
)
messageBtn
.
addEventListener
(
'click'
,
e
=> {
console
.
log
(
message
.
value
)
socket
.
emit
(
'new_message'
, {
message
:
message
.
value
})
message
.
value
=
''
})
socket
.
on
(
'receive_message'
,
data
=> {
console
.
log
(
data
)
let
listItem
=
document.
createElement
(
'li'
)
listItem
.
textContent
=
data
.
username
+
': '
+
data
.
message
listItem
.
classList
.
add
(
'list-group-item'
)
messageList
.
appendChild
(
listItem
)
})
Whenever there is a receive_message event on the client-side, we will change our DOM so as to render the message into the screen.
On receipt of a new_message event on the back-end side a new event should be emitted to all the clients and for that we use io.sockets.emit () function. You can change your connection event in your app.js file as shown below.
io
.
on
(
'connection'
,
socket
=> {
console
.
log
(
"New user connected"
)
socket
.
username
=
"Anonymous"
socket
.
on
(
'change_username'
,
data
=> {
socket
.
username
=
data
.
username
})
//handle the new message event
socket
.
on
(
'new_message'
,
data
=> {
console
.
log
(
"new message"
)
io
.
sockets
.
emit
(
'receive_message'
, {
message
:
data
.
message
,
username
:
socket
.
username
})
})
})
During the new_message event the server will emit a receive_message to all connected clients with data about the ne message. The sender of the message and all the users connected to the server will be receiving this event and the new message will be displayed on their chat-room interfaces.
Now you can open your web application in your browser and can start chatting. Using two separate browsers you can connect to the chat-room and try with the ‘sending messages’ feature. You can see that the messages sent by a user appear instantly on the application interfaces of both users.
How to add the “I’m Typing” feature?
This feature will improve the quality of user-experience and makes the application more ‘real-time’. Whenever there is a keypress, a new event listener will be added to the input box so as to create a typing event. When keypress on the message input box indicates that user is typing a message, the typing event conveys to the server that the user is typing is typing a message. The typing event emitted by the server is listened by the client-side also to know whether another user is typing currently and shows the message on the user interface.
The following code is to be added inside the connection function in chatroom.js.
let
info
=
document.
querySelector
(
'.info'
)
message
.
addEventListener
(
'keypress'
,
e
=> {
socket
.
emit
(
'typing'
)
})
socket
.
on
(
'typing'
,
data
=> {
info
.
textContent
=
data
.
username
+
" is typing..."
setTimeout
(() => {
info
.
textContent
=
''
},
5000
)
})
When one user is typing, other users see the text “is typing …” for a duration of 5 seconds.
As the next step, we set up the back-end to manage the typing events. Here we use the following code:
socket
.
on
(
'typing'
,
data
=> {
socket
.
broadcast
.
emit
(
'typing'
, {
username
:
socket
.
username
})
})
For notifying the connected clients, socket.io makes use of the broadcast function. When broadcast is used, all connected users except the one who types the message will receive the typing event from the server. Hence, all users except the one who is typing will be shown the text “…is typing”.
By way of connecting to the chat-room from two browsers, you can see and understand clearly how it works in real-time.
Conclusion
We have seen in detail how to create a real-time chat-room application using Node.js. We can improve the chat-room by adding more amazing features.
if you are looking for highly code based NodeJS Development Company India then you are right place landed here. We are providing high quality and professional Web Development. Hire NoDEJS Developer Today for your nodejs requirements.