What is Node.js?

On the modern web, it’s hard to ignore the ubiquity of Node.js. Node.js is a free and open-source platform, runs on javascript that allows you to develop web applications quickly.To understand why you should use Node.js and which types of applications you can build with Node.js, here’s some information to get you started.

Why Node.js?

It uses non-blocking I/O and event-driven architecture that makes it efficient and light-weight.

  • It is built on Chrome’s V8 JavaScript engine-- an open source engine that accepts JavaScript code and quickly compiles it into machine code.
  • It uses npm package manager (a largest ecosystem of open-source library). It contains all the files you need for the module.

Click here https://www.npmjs.com/ to download thousands of free packages for your application.

Types of Applications You Can Build With Node.js

1. Internet of Things (IoT)

IoT is a concept of connecting physical devices among each other with the help of the internet. These devices are embedded with sensors, actuators, and beacons that enable them to send and exchange data. From business and home security, education and automobiles, healthcare and industrial equipment, agriculture and transport, to travel, insurance and entertainment, the IoT have spread rapidly across business sectors. With the popularity of IoT, Node.js has become one of the most prominent solutions for businesses to develop their public and private IoT devices.

Why Node.js for IoT systems?

1. Node streams

There are millions of devices on IoT network that are generating and processing a huge amount of data. Node.js is capable of handling the IoT network through streams. Just like strings or arrays, streams are a collection of data. It is used to read data from the source and write data to a destination. Unlike strings or arrays, the Node.js stream doesn’t require to fit in the memory and this makes it a robust and powerful when working with voluminous data of IoT systems.

There are 4 types of stream in Node.js-

  1. Writable- It is used for the write operation.
  2. Readable- It is used for reading operation.
  3. Duplex- It can be used for both write and read operation.
  4. Transform- A type of Duplex stream that can transform or modify the data as it is read or written.

With Node streams, it’s easy to process multiple concurrent requests from various devices.

2. Based on Event-driven architecture

With the event-driven architecture of Node.js, it can easily manage a plethora of sudden requests and data arrivals from IoT devices. Node.js uses a module called EventEmitter that enables you to incorporate event-driven programming in your project. EventEmitter releases the number of events so that the main loop can trigger a callback function as soon as a loop detects any new event.

Look at the code snippet given below:

const EventEmitter = require('events').EventEmitter;
const myEventEmitter = new EventEmitter;

It’s easy to get started with event-driven driven programming in Node.Js. All you have to do is to use the EventEmitter class. This class can be accessed through the ‘events’ module. Event-driven programming approach in Node.js will eradicate any server-down or server-error issues in IoT network.

3.  Follows Asynchronous programming model

In traditional synchronous programming, your program gets stuck as other processes in the queue will be blocked until the execution of the previous process. To address this issue, Node.js has introduced asynchronous programming model. It enables other processes to continue before the execution of the previous process. This method enables the Node.js to handle heavy input/output operations in less time on the IoT network.

4. NPM package manager

NPM is a package manager of Node.js that is embedded with various powerful IoT modules. You can use these modules to create robust and scalable IoT applications.

2. Real-time chats

Real-time chat is a communication channel that offers live transmission of messages (including text, videos, files, etc.) from sender to receiver via the internet. Real-time chat includes one-to-one chat and one-to-many group chats and builds on varieties of tools like: instant messenger (IM), internet relay chat (IRC), etc. For example- WhatsApp, Google Talk, Skype, and Facebook Messenger.

Why Node.js for real-time chats?

Node.js offers all basic services and components required for building real-time chats. Read the following to know why Node.js is the most preferred solution for real-time chat applications:

  • Powerful Node APIs

Node.js APIs depends on event-driven architecture in which EventEmitters periodically emits events to call listener objects. All the functions associated with the events are called synchronously and all values returned by the call listeners will be discarded and neglected. But, APIs of Node.js enables you to switch on the asynchronous mode by using process.nextTick() or setImmediate() methods in your code.

Let’s look at the code snippet given below:

const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', function(a, b) {
setImmediate(() => {
console.log('this happens asynchronously');
});
function cb(){
console.log('processed in next iteration',a,b);
}
process.nextTick(cb)
console.log('processed in first iteration',a,b);
});
myEmitter.emit('event', 'Zibtek', 'Club');

With this functionality of Node.js, it becomes easy to implement-

  1. server-sent events - A server-sent event is when a web page gets updates (including news feeds, Twitter/Facebook updates, sports results) from a server automatically. It is widely used in real-time applications and instant messaging systems.
  2. Push notification technology- With Node.js, it’s easy to use push notification technology with real-time chat applications. Push notification technology is a brief message in the form of alerts or updates that are sent to the users on their mobile phones. This technology has evolved from a conventional message delivery system to an interactive and advanced medium.
  • Node.js WebSockets

Node.js also works well with WebSockets.WebSocket is a protocol that is used to build web-based data streaming applications and real-time communication applications. It enables the fast two-way exchange of messages between the client and the server and deploys real-time applications easily and efficiently.

Why WebSockets?

1. Enables a seamless real-time communication

Client’s subscription to server-sent events is free in WebSockets. It enables you to easily broadcast your messages to every connected client.

2. Data stream processing

With WebSockets, it is easy to stream binary data between server and client. This, in turn, makes it suitable for stream processing tasks such as image or video processing apps.

Implementing real-time chat app with Node.js WebSockets

Node.js WebSocket API for the chat server is embedded in the socket.io npm package. Socket.io allows for bidirectional real-time event-based communication. It comprised of-

Attaching socket.io to simple HTTP server is an initial step to building a real-time chat app.

Look at the code snippet given below:

const server = require('http').createServer()
const io = require('socket.io')(server)
io.on('connection', function (client) {
client.on('register', handleRegister)
client.on('join', handleJoin)
client.on('leave', handleLeave)
client.on('message', handleMessage)
client.on('chatrooms', handleGetChatrooms)
client.on('availableUsers', handleGetAvailableUsers)
client.on('disconnect', function () {
console.log('client disconnect...', client.id)
handleDisconnect()
})
client.on('error', function (err) {
console.log('received error from client:', client.id)
console.log(err)
})
})
server.listen(3000, function (err) {
if (err) throw err
console.log('listening on port 3000')
})

io.on(‘connection’, cb) is used to listen incoming socket connections. You can attach multiple event listeners to the stream after the new client connects. The disconnect and error events are pre-defined and all other events are custom events that are used to implement chat API. After this, you need to connect the socket server to the client by using const io = require('socket.io-client') and implement API.

3. Single Page Applications (SPAs)

A single-page application is a web application that runs inside a web browser and serves an astounding user experience (UX). It doesn’t require to load the entire page from the server when users interact with the application. This, in turn, reduces the response time (length of the time taken by the system to respond to the users) of an application. SPA websites present the content in a way that it becomes easy for the users to interact with the website.

Why Node.js for SPAs?

  • Node Express and Node.js to create SPA

Node Express is a robust and flexible web application framework of Node.js that provides a set of features to develop mobile and web applications. To reduce the server load and ensures API sharing across various environments and applications, Node Express and Node.js framework allows you to use routing in order to create a SPA.

Using routing feature in Node Express

Node Express uses HTTP methods-

  1. GET- It provides read-only access to the resource.
  2. PUT- It creates a new resource.
  3. POST- It updates an existing resource.
  4. DELETE- It deletes a resource.

Code snippet to show basic use of routing in Node Express to create the SPA:

var express = require('express');
var app = express();
app.get('/', function(request, response){
// response.send('<h1>Homepage</h1><div>This is homepage.</div>'); // you can also directly write HTML content
response.sendFile(__dirname + '/indexPage.html');
});
app.get('/about', function(request, response){
response.sendFile(__dirname + '/aboutUS.html');
});
app.get('/contact', function(request, response){
response.sendFile(__dirname + '/contactUS.html');
});
app.listen(3000, function(){
console.log('Server running at port 3000: http://127.0.0.1:3000');
});

GET method is used to include indexPage, aboutUS and ContactUS are HTML files.

  • Node.js and the browser use the same language, JavaScript

It enables developers to use the same language, data structures, and modular approaches on both client and server side, optimizing the maintainability of your SPAs.  

4. Microservices architecture

Microservices architecture is an approach to building an application as a set of modular components. Let’s have a look at what the microservices approach is:

  • Application is broken into smaller modules. These modules can exchange information with each other.
  • Each module is continuously developed, tested, and maintained separately.
  • In the end, all these modules are integrated to form an application.

Its purpose is to make applications easy to understand, test, and maintain. This approach helps large enterprises where development teams span over a large geographic area, such as across cities, countries, etc. In recent years, many big companies (including Facebook, Netflix, eBay, Amazon) have adopted microservices architecture to run their unique business processes.

Why Node.js for microservices architecture?

  • Using Docker

For microservices, Node.js is an excellent solution. It uses docker (a conterization tool) to encapsulate microservices in different containers. This, in turn, avoid any issues in between application development environment.

Building Node.js containers with Docker

To build containers, Node.js uses docker-compose up command. This command is used to run services by bringing up the network. Look at the code snippet given below.

#  Run `docker-compose build` to build the images
#  Run `docker-compose up` to run the containers
#  Run `docker-compose down` to remove the containers
version: '3.5'
services:
mysql:
container_name: service_mysql
image: mysql:5.7
volumes:
- ~/datadir/mysql:/var/lib/mysql
ports:
- 3306:3306
- 33060:33060
environment:
MYSQL_ROOT_PASSWORD: root
networks:
- service_network
redis:
container_name: service_redis
image: redis:4.0
volumes:
- ~/datadir/redis:/var/lib/redis
ports:
- 6379:6379
networks:
- service_network
api:
container_name: service_api
build: ./apiapp/
image: service_api
volumes:
- ./apiapp/:/usr/src/app
- /usr/src/app/node_modules
ports:
- 3000:3000
- 9229:9229
depends_on:
- mysql
- redis
- notification
networks:
- service_network
app2:
build: ./notification/
image: service_notification
container_name: service_notify
environment:
- NODE_ENV=local
volumes:
- ./notification/:/usr/src/app
- /usr/src/app/node_modules
ports:
- 4000:4000 # Notification api port
- 9223:9223 # Node debugg port
- 8099:8099 # GRPC port
depends_on:
- mysql
networks:
- service_network
networks:
service_network:
driver: bridge
name: service_network

There are 4 containers in this docker compose file. After this, you need to create API to connect these containers with a Mysql database.

  • Creates easy-to-use API to connect Node containers with Mysql

Node.js can create easy-to-use APIs for microservices. It helps modular the node containers to communicate better with each other.

Look at the code snippet given below:

const mysql = require('mysql2/promise');
const config =  {
user: 'root',
password: 'root',
database: 'testdb',
host: 'mysql',
connectTimeout: 80000,
};
mysql.createConnection(config)
.then((connection) => {
console.log(`connection established to local ${config.database} database`);
global.MYconnection = connection;
})
.catch((e) => {
console.log(e);
eventEmitter.emit('connectionFailed', 'Destination');
});

Want to build amazing applications? Contact us today! Our Node.js experts can deliver robust, powerful, flexible and scalable application that can add value to your business.