CA938_Unit4_NodeJS
CA938_Unit4_NodeJS
What is Node.js?
Node.js is an open-source server side runtime environment built on Chrome's V8
JavaScript engine.
It provides an event driven, non-blocking (asynchronous) I/O and cross-platform
runtime environment for building highly scalable server-side application using
JavaScript.
Event-Driven: Node.js listens for events and processes them using callback functions,
which makes it highly responsive and efficient.
Non-Blocking (Asynchronous) I/O: Node.js performs I/O operations asynchronously,
allowing other tasks to proceed without waiting for the I/O operation to complete,
leading to better performance.
Cross-Platform Runtime Environment: Node.js runs on various operating systems,
enabling code portability and simplifying development and deployment.
Node.js can be used to build different types of applications such as command line
application, web application, real-time chat application, REST API server etc.
However, it is mainly used to build network programs like web servers, similar to
PHP, Java, or ASP.NET.
Moreover, it operates on a single threaded event based loop to make all executions
non-blocking.
However, you cannot consider Node.js as not a framework and it has nothing to do
with the PHP, .NET or JAVA.
Key Features:
o Event-Driven Architecture: Asynchronous and non-blocking I/O.
o Single-Threaded Model: Uses a single thread for handling multiple
connections.
o NPM (Node Package Manager): Rich ecosystem of libraries and modules.
High Performance:
One of the most important features of node.js is the ability to create lightning-fast
apps that produce results in seconds.
Its event-driven, single-threaded design rapidly processes several simultaneous
requests without clogging the RAM. Additionally, its event-loop and non-blocking
I/O operations allow code to be executed at a rate that indirectly influences the
application's overall performance.
Scalability
One of the Node.js advantages is that developers can easily grow applications in both
horizontal and vertical orientations. The applications can be horizontally scaled by
adding additional nodes to the existing system.
Because Node.js is designed to handle many connections concurrently, it is well-
suited for horizontal scaling. You can add more servers to distribute the workload
without significant changes to the codebase - If your application is receiving more
traffic, you can deploy additional instances of your application on multiple servers. A
load balancer can then distribute the incoming requests across these instances,
ensuring that no single server is overwhelmed.
Furthermore, during the vertical scaling of the application, Node.js allows you to add
extra resources to single nodes. As a result, it is extremely scalable and offers a
superior alternative to existing JavaScript servers - Node.js is efficient in terms of
CPU and memory usage, which allows you to effectively utilize more powerful
hardware to handle more operations within a single machine.
Easy to Learn
Most frontend developers are familiar with JavaScript because it is one of the most
extensively used programming languages.
It will be lot easier for them to get started using Node.js on the backend. It is simpler
to understand Node.js, and working with it takes less time.
Cost-Effective
Node.js allows programmers to develop server-side JavaScript and frontend
JavaScript codes with simplicity. One of the major node.js advantages is that it
eliminates the need for two resource teams, saving time, money, and energy for
overall project development.
LinkedIn's development team switched from Ruby on Rails to Node.js, and the
benefits of Node.js helped them gain performance. They lowered the number of
servers from 30 to only three. They began delegating and utilizing resources more
effectively, changing their attention from debugging to app development.
Extensibility
Node.js offers a lot of extensibility, which means it can be changed and improved to
fit unique requirements.
Data may be sent between the web server and the client using the JSON format. It
also has APIs for constructing HTTP, TCP, and DNS servers, among other features.
MCA Semester 3 CA938 : AWD (Unit 4 - NodeJS)
In the traditional web server model, each request is handled by a dedicated thread
from the thread pool.
If no thread is available in the thread pool at any point of time, then the request
waits till the next available thread.
Dedicated thread executes a particular request and does not return to thread pool
until it completes the execution and returns a response.
Node.js process model increases the performance and scalability with a few
requirements. Node.js is not fit for an application which performs CPU-intensive
operations like image processing or other heavy computation work because it takes
time to process a request and thereby blocks the single thread.
MCA Semester 3 CA938 : AWD (Unit 4 - NodeJS)
Install Node.js
Node.js development environment can be setup in Windows, Mac, Linux and Solaris. The
following tools/SDK are required for developing a Node.js application on any platform.
1. Node.js
2. Node Package Manager (NPM)
3. IDE (Integrated Development Environment) or TextEditor
NPM (Node Package Manager) is included in Node.js installation since Node version 0.6.0.,
so there is no need to install it separately.
Node.js Module
Each module in Node.js has its own context, so it cannot interfere with other modules or
pollute global scope. Also, each module can be placed in a separate .js file under a separate
folder.
1. Core Modules
2. Local Modules
3. Third Party Modules
Node.js is a light weight framework. The core modules include bare minimum
functionalities of Node.js. These core modules are compiled into its binary
distribution and load automatically when Node.js process starts. However, you need
to import the core module first in order to use it in your application.
The following table lists some of the important core modules in Node.js.
The http module is a core module in Node.js that provides the functionality to create
HTTP servers and make HTTP requests. It is one of the fundamental building blocks
for building web applications and services in Node.js. This module supports both
server-side and client-side operations.
Key Features
o Creating HTTP Servers: Easily create HTTP servers that can handle incoming
requests and send responses.
o Making HTTP Requests: Facilitate making HTTP requests to other servers
for client-side operations.
Importing the Module
o const http = require('http');
Creating an HTTP Server
- Request (IncomingMessage)
Properties:
req.method The HTTP method used for the request e.g., 'GET', 'POST'
req.url The URL of the request.
req.headers An object containing the request headers.
Methods:
req.on('data',callback): Adds a listener for the 'data' event, which is emitted when a
chunk of data is available.
- Response (http.ServerResponse)
Properties:
res.statusCode The HTTP status code of the response (default is 200).
res.statusMessage The HTTP status message associated with the status code (default
is 'OK').
Methods:
res.setHeader(name, value) Sets a single header value for the response
MCA Semester 3 CA938 : AWD (Unit 4 - NodeJS)
Example:
2. fs module
The fs module in Node.js provides a comprehensive API for interacting with the file
system. It offers both asynchronous and synchronous methods for reading, writing,
appending, deleting files, and managing directories.
Key Features
Methods
Example:
3. Url Module
The url module in Node.js provides utilities for URL resolution and parsing. This
module allows for parsing URLs, constructing URLs, resolving URLs, and generating
URLs.
Importing the module:
MCA Semester 3 CA938 : AWD (Unit 4 - NodeJS)
Properties:
Example:
Local modules are modules created locally in your Node.js application. These
modules include different functionalities of your application in separate files and
folders.
You can also package it and distribute it via NPM, so that Node.js community can
use it. For example, if you need to connect to MongoDB and fetch data then you can
create a module for it, which can be reused in your application.
console.log(msg);
Let's write simple logging module which logs the information, warning or error to
the console.
In Node.js, module should be placed in a separate JavaScript file. So, create a Log.js
file and write the following code in it.
var log = {
info: function (info) {
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
};
module.exports = log
In the above example of logging module, we have created an object with three
functions - info(), warning() and error(). At the end, we have assigned this object
to module.exports. The module.exports in the above example exposes a log object
as a module.
The module.exports is a special object which is included in every JS file in the
Node.js application by default. Use module.exports or exports to expose a function,
object or variable as a module in Node.js.
To use local modules in your application, you need to load it using require() function
in the same way as core module. However, you need to specify the path of JavaScript
file of the module.
The following example demonstrates how to use the above logging module contained
in Log.js.
In the above example, app.js is using log module. First, it loads the logging module
using require() function and specified path where logging module is stored. Logging
module is contained in Log.js file in the root folder. So, we have specified the path
'./Log.js' in the require() function. The '.' denotes a root folder.
The require() function returns a log object because logging module exposes an object
in Log.js using module.exports. So now you can use logging module as an object and
call any of its function using dot notation e.g myLogModule.info() or
myLogModule.warning() or myLogModule.error()
MCA Semester 3 CA938 : AWD (Unit 4 - NodeJS)
Third-party modules: Third-party modules are modules that are available online using the
Node Package Manager(NPM). These modules can be installed in the project folder or
globally. Some of the popular third-party modules are Mongoose, express, angular, and
React.
Examples:
o Express framework - flexible Node js web application framework
o Socket.io - real-time bidirectional event-based communication
o Jade - high-performance template engine
o mongoDB -node.js driver for MongoDB.
o Restify - similar to express for building REST APIs
o Bluebird -promise library
JavaScript facilitates the capability to store and transport the data while sending the
data from a server to a web page with the help of JSON.
JSON (JavaScript Object Notation) is a language-independent lightweight data
interchange format, easy to read and write.
JSON provides different methods that help to convert the JS object to a string or
provides parsing of a JSON string, which is written in a JSON format to a JavaScript
object.
For this, JSON.parse() & JSON.stringify methods are used. In this article, we will see
JSON.parse() method & JSON.stringify method, their implementation & difference
between them.
1. JSON.stringify() Method
o It is used to convert JavaScript objects into JSON strings. This method only
takes a single argument, and that argument is an object to be converted into
JSON strings.
o It works oppositely to JSON.parse() method.
o JSON.stringify can take replacer parameters as a function, we can write logic
on key-value pairs of objects.
o While receiving data from a web server (like a node server), data has to be in
the string format, & after parsing data with JSON.parse(), the data become
an Object. The format of the Date is not allowed in JSON, So you can include
the Date in the string.
o Syntax: JSON.stringify(data,replacer,space)
- Data: JSON Object variable or data object
- Replacer:
- String
- The first one is a replacer function. The second is a String or Number
value to use as a space in the returned string.
o Examples
const myInfo = {
Name: "Bob",
Age:22,
Department : "Computer Science and Engineering"
}
const Obj = JSON.stringify(myInfo);
console.log(Obj)
let userObj = {
name: "Sammy",
email: "sammy@example.com",
plan: "Pro"
};
console.log(userStrReplacer);
2. JSON.parse() Method
const myInfo = `{
"Name": "GFG",
"Age":22,
"Department" : "Computer Science and Engineering"
}`
Convert data JavaScript object into JSON Convert a JSON string into a JavaScript
string. Object.
while sending data to a web server, data has While receiving data from the web server
to be in string format. data has to be in the string.
MCA Semester 3 CA938 : AWD (Unit 4 - NodeJS)
It allow 2 extra (optional) parameters, i.e It allow one extra (optional) parameter, i.e
value, replacer, and space, for eg., reviewer, for eg, JSON.parse(value,
JSON.stringify(value, replacer, space). reviewer).