0% found this document useful (0 votes)
7 views

node JS unit-1-4

This document provides an introduction to JavaScript and Node.js, covering their features, applications, and key concepts such as asynchronous programming and the event loop. It highlights JavaScript's role in web development and Node.js's capabilities as a server-side environment, emphasizing the benefits of asynchronous programming for performance and scalability. The document also discusses error handling and best practices for writing asynchronous code in Node.js.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

node JS unit-1-4

This document provides an introduction to JavaScript and Node.js, covering their features, applications, and key concepts such as asynchronous programming and the event loop. It highlights JavaScript's role in web development and Node.js's capabilities as a server-side environment, emphasizing the benefits of asynchronous programming for performance and scalability. The document also discusses error handling and best practices for writing asynchronous code in Node.js.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

UNIT – I INTRODUCTION TO JAVASCRIPT AND NODEJS

Introduction to JavaScript - Introduction to Node JS - Asynchronous


Programming in Node.js – Event loop in Node JS - Architecture of Node JS
- Examples of Node JS

1.1 Introduction to JavaScript

● JavaScript is a lightweight, cross-platform, single-


threaded, and interpreted compiled programming language.
● It is also known as the scripting language for webpages. It is well-known
for the development of web pages, and many non-browser environments
also use it.
● JavaScript is a high-level programming language commonly used for
creating interactive effects within web browsers.
● It was initially developed by Netscape as a client-side scripting language
but has since evolved into a powerful tool for both client-side and server-
side development.
● JavaScript (js) is a object-oriented programming language

Features of JavaScript

There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in


execution environments.
2. JavaScript follows the syntax and structure of the C programming
language. Thus, it is a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly
cast (depending on the operation).
4. JavaScript is an object-oriented programming language that uses
prototypes rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including,
Windows, macOS, etc.
8. It provides good control to the users over the web browsers.
Application of JavaScript

JavaScript is used to create interactive websites. It is mainly used for:

o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box,
confirm dialog box and prompt dialog box),
o Displaying clocks etc.

JavaScript Example
<script>
document.write("Hello JavaScript by JavaScript");
</script>

Key Concepts:

1. Syntax and Basics:


o Variables (var, let, const)
o Data types (string, number, boolean, object, array)
o Operators (+, -, *, /, %, etc.)
o Control structures (if, else, switch, for, while)
2. Functions:
o Function declarations
o Function expressions
o Arrow functions
3. Objects and Arrays:
o Creating and manipulating objects and arrays
o Iterating over arrays and objects
4. Event Handling:
o Adding event listeners
o Handling events like click, submit, keypress
5. DOM Manipulation:
o Selecting elements (getElementById, querySelector)
o Modifying element content and attributes

1.2 Introduction to Node JS


● Node.js is an open-source and cross-platform JavaScript runtime
environment.
● Node.js runs the V8 JavaScript engine, the core of Google Chrome,
outside of the browser.
● A Node.js app runs in a single process, without creating a new thread for
every request.
● Node.js is an open source server environment
● Node.js is free
● Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X,
etc.)
● Node.js uses JavaScript on the server

● JavaScript Runtime: Node.js runs on the V8 JavaScript engine, which is


also the core engine behind Google Chrome. However, unlike the browser
context, Node.js executes JavaScript code outside of the browser.
● Single Process Model: A Node.js application operates within a single
process, avoiding the need to create a new thread for every request. This
design choice contributes to Node.js’ performance.
● Asynchronous I/O: Node.js provides a set of asynchronous I/O
primitives in its standard library. These primitives prevent JavaScript code
from blocking, making non-blocking behavior the norm. When performing
I/O operations (e.g., reading from the network, accessing databases, or the
filesystem), Node.js doesn’t waste CPU cycles waiting. Instead, it resumes
operations when the response arrives.
● Concurrency Handling: Node.js efficiently handles thousands of
concurrent connections using a single server. It avoids the complexities of
managing thread concurrency, which can lead to bugs.
● JavaScript Everywhere: Frontend developers familiar with JavaScript can
seamlessly transition to writing server-side code using Node.js. You don’t
need to learn a different language.
● ECMAScript Standards: Node.js supports the latest ECMAScript
standards. You can choose the version you want to use, independent of
users’ browser updates.

*** ECMAScript (European Computer Manufacturers


Association Script)
Advantages of Node JS

● Easy to Get Started: Node.js is beginner-friendly and ideal for prototyping


and agile development.
● Scalability: It scales both horizontally and vertically.
● Real-Time Web Apps: Node.js excels in real-time synchronization.
● Fast Suite: It handles operations quickly (e.g., database access, network
connections).
● Unified Language: JavaScript everywhere—frontend and backend.
● Rich Ecosystem: Node.js boasts a large open-source library and supports
asynchronous, non-blocking programming.
● Extremely fast: Node.js is built on Google Chrome's V8 JavaScript
Engine, so its library is very fast in code execution.
● I/O is Asynchronous and Event Driven: All APIs of Node.js library are
asynchronous i.e. non-blocking. So a Node.js based server never waits for
an API to return data. The server moves to the next API after calling it
and a notification mechanism of Events of Node.js helps the server to get
a response from the previous API call. It is also a reason that it is very
fast.
● Single threaded: Node.js follows a single threaded model with event
looping.
● No buffering: Node.js cuts down the overall processing time while
uploading audio and video files. Node.js applications never buffer any
data. These applications simply output the data in chunks.
● Open source: Node.js has an open source community which has
produced many excellent modules to add additional capabilities to
Node.js applications.

Concepts

The following diagram depicts some important parts of Node.js which we will
discuss in detail in the subsequent chapters.
Examples:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!');
}).listen(8080);
1.3 Asynchronous Programming in Node.js
● Asynchronous programming is a programming paradigm that allows tasks
to run independently of each other, improving performance and
responsiveness in applications.
● In Node.js, asynchronous programming is essential due to its single-
threaded, event-driven architecture.
● By leveraging asynchronous techniques, developers can ensure that their
applications remain responsive and can handle multiple requests
concurrently.

1.3.1 Synchronous vs. Asynchronous Programming


synchronous programming
● In synchronous programming, tasks are executed one after another,
blocking the execution until the previous task completes.
● This can lead to performance issues, especially in scenarios where tasks
involve waiting for external resources, such as file I/O or network
requests.
Asynchronous programming
● Asynchronous programming, on the other hand, allows tasks to be
executed concurrently without waiting for each other to complete.
● This enables the Node.js event loop to efficiently manage multiple
operations simultaneously, resulting in improved performance and
scalability.

1.3.2 How to write asynchronous function for Node.js

● The asynchronous function can be written in Node.js using ‘async’


preceding the function name.
● The asynchronous function returns an implicit Promise as a result. The
async function helps to write promise-based code asynchronously via the
event loop.
● Async functions will always return a value. Await function can be used
inside the asynchronous function to wait for the promise.
● This forces the code to wait until the promise returns a result.
● Install async from npm in Node.js using the following command:

npm i async

****NPM (Node Package Manager) is the default package manager for Node and is written
entirely in JavaScript.

1.3.3 How to Write Asynchronous Code


● In many JavaScript applications, the code is performed one line at a time.
● Node.js async execution refers to the fact that the lines are executed in the
sequence in which they were written, one after the other. While some of
your commands to the computer are urgent, some are not.
● It is necessary to wait for the data to be returned before working on a
network request, for example. While waiting for the network request to
finish, time would be lost if another code was not executed.
● Asynchronous programming, in which lines of code are executed in a
different sequence than the one in which they were created, is used to
tackle this issue.
● Asynchronous programming, on the other hand, allows us to focus on
other tasks while we wait for lengthy operations, such as network
requests, to complete.
● One thread in a computer process executes JavaScript code. One
instruction at a time is executed in a synchronous manner on this thread.
● This means that if we try to run a long task on this thread, the rest of the
code will be blocked until the job is finished.
● We can circumvent this difficulty by using JavaScript's asynchronous
programming tools to delegate long-running activities to a separate
thread. The code required to handle the task data is returned to the main
single thread after the job is complete.
● The Event Loop, a Node.js async await construct that completes a new
job while waiting for another, will be explained in detail in this article.
● Create an asynchronous software to get a list of Studio Ghibli movies and
save the data to a CSV file using a Studio Ghibli API.
● Callbacks, promises, and the async/await keywords will all be used to
write asynchronous programs.

1.3.4 Benefits of Asynchronous Programming


Asynchronous programming offers several benefits for Node.js applications:

● Improved Performance: By avoiding blocking operations, asynchronous


programming allows the application to continue executing other tasks while
waiting for I/O operations to complete. This leads to faster response times
and better resource utilization.

● Scalability: Asynchronous programming enables Node.js applications to


handle a large number of concurrent requests without significant
performance degradation. This scalability is crucial for building high-
performance web servers and real-time applications.

● Responsive User Interfaces: Asynchronous programming ensures that the


user interface remains responsive even when performing time-consuming
operations. This enhances the overall user experience and prevents
applications from becoming unresponsive or freezing.

Asynchronous Programming in Node.js


Node.js provides several mechanisms to implement asynchronous
programming. Let’s explore some of the most commonly used techniques:

Event-Driven Architecture
● Node.js follows an event-driven architecture, where tasks are triggered by
events and associated event handlers. Events can be I/O operations,
timers, or user interactions.
● This event-driven model allows developers to write non-blocking code
and respond to events as they occur.
Callbacks
● Callbacks are a fundamental mechanism in Node.js for handling
asynchronous operations.
● A callback is a function that is passed as an argument to another function
and gets executed once the operation completes.
● This allows for the continuation of code execution without blocking.
// Simulating an asynchronous task
function simulateAsyncTask(callback) {
setTimeout(() => {
const randomNumber = Math.random();
if (randomNumber > 0.5) {
callback(null, 'Task completed successfully!');
} else {
callback(new Error('Task failed!'), null);
}
}, 2000); // Simulating a delay of 2 seconds
}

// Using the callback


simulateAsyncTask((error, result) => {
if (error) {
console.error(error); // Task failed!
} else {
console.log(result); // Task completed successfully!
}
});

Promises
● Promises provide a more structured way to handle asynchronous
operations in Node.js.
● A promise represents the eventual completion or failure of an
asynchronous operation and allows chaining multiple asynchronous
operations together. Promises improve code readability and make error
handling easier.
// Simulating an asynchronous task
function simulateAsyncTask() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const randomNumber = Math.random();
if (randomNumber > 0.5) {
resolve('Task completed successfully!');
} else {
reject(new Error('Task failed!'));
}
}, 2000); // Simulating a delay of 2 seconds
});
}

// Using the Promise


simulateAsyncTask()
.then((result) => {
console.log(result); // Task completed successfully!
})
.catch((error) => {
console.error(error); // Task failed!
});

Async/Await
● Introduced in ES2017, async/await is a modern approach to writing
asynchronous code in a more synchronous style.
● By using the async keyword to define an asynchronous function
and await to wait for promises to resolve, developers can write code that
resembles synchronous programming while leveraging the benefits of
synchronicity.
// Simulating an asynchronous task
function simulateAsyncTask() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const randomNumber = Math.random();
if (randomNumber > 0.5) {
resolve('Task completed successfully!');
} else {
reject(new Error('Task failed!'));
}
}, 2000); // Simulating a delay of 2 seconds
});
}

// Using async/await
async function executeAsyncTask() {
try {
const result = await simulateAsyncTask();
console.log(result); // Task completed successfully!
} catch (error) {
console.error(error); // Task failed!
}
}
// Calling the async function
executeAsyncTask();

Handling Errors in Asynchronous Code


Error handling is crucial when working with asynchronous code to ensure the
stability and reliability of applications. Different techniques are used depending
on the chosen asynchronous pattern.

Error-First Callbacks
In Node.js, error-first callbacks are a convention where the first parameter of a
callback function represents an error object. By following this convention,
developers can easily handle errors in asynchronous code and propagate them to
the appropriate error-handling mechanisms.

Promises and Error Handling


Promises provide a built-in mechanism for error handling through
their catch method. By chaining .catch() After a promise, errors can be caught
and handled gracefully, preventing them from bubbling up and crashing the
application.

Try/Catch with Async/Await


When using async/await, error handling can be done using traditional try/catch
blocks. This allows developers to catch and handle errors within the same scope
as synchronous code, making error handling more intuitive.

Best Practices for Asynchronous Programming in Node.js


To master asynchronous programming in Node.js, it’s important to follow best
practices that ensure code readability, maintainability, and performance.
Avoiding Callback Hell
Callback Hell refers to the situation where callbacks are nested within each
other, leading to code that is difficult to read and maintain. To avoid this,
developers can use techniques such as modularization, promises, or async/await
to flatten the code and make it more manageable.

Proper Error Handling


Handling errors properly is essential in asynchronous programming. Ensure that
errors are caught and handled at appropriate levels, preventing unhandled
rejections and crashes. Implement robust error logging and use error monitoring
tools to identify and fix issues proactively.

Utilizing Promises and Async/Await


Promises and async/await provide more structured and readable ways to handle
asynchronous code. Whenever possible, prefer using promises or async/await
over raw callbacks to improve code clarity and maintainability.

Using Async Libraries


Leverage existing asynchronous libraries in the Node.js ecosystem that provide
helpful abstractions and utilities for common asynchronous tasks. Libraries such
as async.js or bluebird can simplify complex asynchronous operations and
provide additional functionalities.

The Node.js Event Loop

Node is a single-threaded event-driven platform that is capable of running non-


blocking, asynchronous programming. These functionalities of Node make it
memory efficient.

1.4 The Event Loop in Node js

● The event loop allows Node to perform non-blocking I/O operations


despite the fact that JavaScript is single-threaded.
● It is done by assigning operations to the operating system whenever and
wherever possible.

1.4.1 Importance of Event Loop


● Most operating systems are multi-threaded and hence can handle multiple
operations executing in the background.
● When one of these operations is completed, the kernel tells Node.js, and
the respective callback assigned to that operation is added to the event
queue which will eventually be executed.

1.4.2 Features of Event Loop:


● An event loop is an endless loop, which waits for tasks, executes them, and
then sleeps until it receives more tasks.
● The event loop executes tasks from the event queue only when the call stack
is empty i.e. there is no ongoing task.
● The event loop allows us to use callbacks and promises.
● The event loop executes the tasks starting from the oldest first.

Example

console.log("This is the first statement");

setTimeout(function(){

console.log("This is the second statement");

}, 1000);

console.log("This is the third statement");

output

This is the first statement


This is the third statement
This is the second statement

Working of the Event loop

● When Node.js starts, it initializes the event loop, processes the provided
input script which may make async API calls, schedules timers, then
begins processing the event loop.
● In the previous example, the initial input script consisted of console.log()
statements and a setTimeout() function which schedules a timer.
● When using Node.js, a special library module called libuv is used to
perform async operations. This library is also used, together with the back
logic of Node, to manage a special thread pool called the libuv thread
pool.
● This thread pool is composed of four threads used to delegate operations
that are too heavy for the event loop.
● I/O operations, Opening and closing connections, setTimeouts are
examples of such operations.
● When the thread pool completes a task, a callback function is called
which handles the error(if any) or does some other operation.
● This callback function is sent to the event queue.
● When the call stack is empty, the event goes through the event queue and
sends the callback to the call stack.
● The following diagram is a proper representation of the event loop in a
Node.js server:

Phases of the Event loop:


The event loop in Node.js consists of several phases, each of which performs a
specific task. These phases include:
The following diagram shows a simplified overview of the event loop order of
operations:
1. Timers: This phase processes timers that have been set using setTimeout()
and setInterval().
Here is an example of how the timers phase works:

console.log('Start');

setTimeout(() => {

console.log('Timeout callback');

}, 2000);

console.log('End');

In this example, the setTimeout() function is called with a callback that will
print “Timeout callback” to the console after 2000 milliseconds (2 seconds).
This function is added to the message queue in the timers phase, and the event
loop will process it after the synchronous code is executed. The output will be:
Start
End
Timeout callback
As you can see, the “Timeout callback” is printed after 2 seconds, after the
“Start” and “End” are printed, because the setTimeout() function is non-
blocking and its callback is processed by the event loop after the execution of
the synchronous code.

2. Pending Callbacks: This phase processes any callbacks that have been
added to the message queue by asynchronous functions.
Here is an example of how the pending callbacks phase works:

console.log('Start');

setImmediate(() => {

console.log('Immediate callback');

});

console.log('End');

In this example, the setImmediate() function is called with a callback that will
print “Immediate callback” to the console. This function is added to the
message queue in the pending callbacks phase, and the event loop will process it
after the timers phase. The output will be:
Start
End
Immediate callback
3. Idle, Prepare: The “idle.ignore” phase is not a standard phase of the event
loop in Node.js. It means it’s Used internally only. The “idle” phase is a period
of time during which the event loop has nothing to do and can be used to
perform background tasks, such as running garbage collection or checking for
low-priority events.
“idle.ignore” is not an official phase of the event loop, it is a way to ignore the
idle phase, meaning that it will not use the time of the idle phase to perform
background tasks.
An example of using idle.ignore can be:

const { idle } = require('idle-gc');

idle.ignore();
Here we are using the idle-gc package, which allows you to ignore the idle
phase. This can be useful in situations where you want to ensure that the event
loop is always busy and that background tasks are not performed.
It’s worth mentioning that, in general, the use of idle.ignore is not
recommended, as it could cause performance issues, we should only use this if
we have a very specific use case that requires it.
4. Poll: This phase is used to check for new I/O events and process any that
have been detected.
Here is an example of how the poll phase works using a readStream:

const fs = require('fs');

const readStream = fs.createReadStream('./file.txt');

console.log('Start');

readStream.on('data', (chunk) => {

console.log(chunk.toString());

});

console.log('End');

In this example, a readStream is created to read the contents of a file. The ‘data’
event is added to the message queue in the poll phase, and the event loop will
process it after the pending callbacks phase. The output will be the content of
the file.

5. Check This phase processes any setImmediate() callbacks that have been
added to the message queue.
Here is an example of how the check phase works:

6. Close callbacks
If a socket or handle is closed abruptly (e.g. socket.destroy()), the 'close' event
will be emitted in this phase. Otherwise it will be emitted
via process.nextTick().
setImmediate() vs setTimeout()
setImmediate() and setTimeout() are similar, but behave in different ways
depending on when they are called.
● setImmediate() is designed to execute a script once the
current poll phase completes.
● setTimeout() schedules a script to be run after a minimum threshold in
ms has elapsed.
The order in which the timers are executed will vary depending on the context
in which they are called. If both are called from within the main module, then
timing will be bound by the performance of the process
(which can be impacted by other applications running on the machine).
1.5 Architecture of Node JS
● Node.js is an extremely powerful JavaScript-based platform that’s built
on Google Chrome's JavaScript V8 Engine, used to develop I/O intensive
web applications like video streaming sites, single-page applications,
online chat applications, and other web apps.
● Node.js is used by large, established companies and newly-minted
startups alike. Open-source and completely free, the platform is used by
thousands of developers around the world. It brings plenty of advantages
to the table, making it a better choice than other server-side platforms
like Java or PHP in many cases.
● In this article we will cover the following topics that will give complete
understanding of Node.js architecture:
o Node.js server architecture
o Parts of the Node.js architecture
o Workflow of Node.js architecture
o Advantages of Node.js architecture
Check out the video below that will help you understand all about the
Node.js architecture.

Web Applications
A web application, as you may already know, is a program that runs on a
server and is rendered by a client browser, using the internet to access all
the resources of that application. It usually can be easily broken down
into three parts:
1. Client
2. Server
3. Database
Client
The user interacts with the front-end part of a web application. The front-
end is usually developed using languages like HTML and CSS styles,
along with extensive usage of JavaScript-based frameworks like ReactJS
and Angular, which help with application design.
Server
● The server is responsible for taking the client requests, performing the
required tasks, and sending responses back to the clients.
● It acts as a middleware between the front-end and stored data to enable
operations on the data by a client.
● Node.js, PHP, and Java are the most popular technologies in use to
develop and maintain a web server.
Database
● The database stores the data for a web application. The data can be
created, updated, and deleted whenever the client requests.
● MySQL and MongoDB are among the most popular databases used to
store data for web applications.
Node.js Server Architecture
● Node.js uses the “Single Threaded Event Loop” architecture to handle
multiple concurrent clients.
● Node.js Processing Model is based on the JavaScript event-based model
along with the JavaScript callback mechanism.
Parts of the Node.js Architecture:

● Requests

Incoming requests can be blocking (complex) or non-blocking (simple),


depending upon the tasks that a user wants to perform in a web application

● Node.js Server

Node.js server is a server-side platform that takes requests from users,


processes those requests, and returns responses to the corresponding users

● Event Queue

Event Queue in a Node.js server stores incoming client requests and passes
those requests one-by-one into the Event Loop

● Thread Pool
Thread pool consists of all the threads available for carrying out some tasks
that might be required to fulfill client requests

● Event Loop

Event Loop indefinitely receives requests and processes them, and then
returns the responses to corresponding clients

● External Resources

External resources are required to deal with blocking client requests. These
resources can be for computation, data storage, etc.

The Workflow of Node.js Architecture:

A web server developed using Node.js typically has a workflow that is quite
similar to the diagram illustrated below. Let’s explore this flow of operations in
detail.

● Clients send requests to the webserver to interact with the web application.
Requests can be non-blocking or blocking:

-Querying for data

-Deleting data

-Updating the data


● Node.js retrieves the incoming requests and adds those requests to the Event
Queue

● The requests are then passed one-by-one through the Event Loop. It checks if the
requests are simple enough to not require any external resources

● Event Loop processes simple requests (non-blocking operations), such as I/O


Polling, and returns the responses to the corresponding clients

A single thread from the Thread Pool is assigned to a single complex request. This
thread is responsible for completing a particular blocking request by accessing the
external resources, such as compute, database, file system, etc.

Once, the task is carried out completely, the response is sent to the Event Loop that
in turn sends that response back to the Client

Advantages of Node.js Architecture

Node.js Architecture comes with several advantages that give the server-side
platform a distinct upper-hand when compared to other server-side languages:

● Handling multiple concurrent client requests is fast and easy

With the use of Event Queue and Thread Pool, the Node.js server enables efficient
handling of a large number of incoming requests.

● No need for creating multiple threads

Event Loop handles all requests one-by-one, so there is no need to create multiple
threads. Instead, a single thread is sufficient to handle a blocking incoming request.

● Requires fewer resources and memory

Node.js server, most of the time, requires fewer resources and memory due to the way it
handles the incoming requests. Since the requests are processed one at a time, the
overall process becomes less taxing on the memory.
All of these advantages contribute to making the servers developed using Node.js
much faster and responsive when compared to those developed using other server
development technologies.

Examples of Node JS

Program – 1
console.log('This example is different!');
console.log('The result is displayed in the Command Line Interface');

output
This example is different!
The result is displayed in the Command Line Interface

Program – 2 : Hello World application using Node.js.

Create a gk1.js file containing the following code:


console.log('Hello World');

Run the file on the Node.js command prompt using the command node
gk1.js i.e. node <file_name>.

Output:

Example 3: Hello World application Receiving the User Input

Create a gfg.js file containing the following code.


console.log(process.argv.slice(2));

The process.argv is used to provide a command line argument to a


program. Use the slice function with 2 as its argument to get all the
elements of argv that come after its second element, i.e. the arguments the
user entered.
The first argument is the location of the Node.js binary which runs the
program and the second argument is the location of the file being run.
UNIT 2 SERVER SIDE PROGRAMMING WITH NODE JS
Introduction to Web Servers – Javascript in the Desktop with NodeJS – NPM –
Serving files with the http module – Introduction to the Express framework –
Server-side rendering with Templating Engines – Static Files - async/await -
Fetching JSON from Express.js
2.1 Introduction to Web Servers
● A web server is a software application or hardware device that stores,
processes, and serves web content to users over the internet.
● It plays a critical role in the client-server model of the World Wide Web,
where clients (typically web browsers) request web pages and resources,
and servers respond to these requests by delivering the requested content.
● Web servers operate on the Hypertext Transfer Protocol (HTTP), which
is the foundation of data communication on the World Wide Web.
● When you enter a website’s URL into your browser, it sends an HTTP
request to the web server hosting that website, which then sends back the
web page you requested, allowing you to view it in your browser.

Web Server Architecture


● Web server architecture refers to the structure and design of web servers,
outlining how they handle incoming requests and deliver web content.
● There are two main approaches to web server architecture:

Single-Tier (Single Server) Architecture:


● In a single-tier architecture, a single server is responsible for both
processing requests and serving web content.
● This is suitable for small websites or applications with low traffic.
However, it has limitations in terms of scalability and fault tolerance. If
the server goes down, the entire service becomes unavailable.

Multi-
Tier (Load-Balanced) Architecture:
● In a multi-tier architecture, multiple servers are used to distribute the
workload and ensure high availability.
● This approach often involves load balancers that evenly distribute
incoming requests across a cluster of web servers.
● Each server can serve web content independently, and if one server fails,
the load balancer redirects traffic to healthy servers, ensuring
uninterrupted service.
Working of Web Servers

A web server works in the following ways:


● Obtain the IP address from domain name: IP address is obtained in two
ways either by searchin it in the cache or requesting DNS Servers
● Requests full URL from Browsers: After fetching IP address a full URL is
demanded from from web server
● Web Server Responds to the request: In accordance with the request a
response is sent by the server in case of successful request otherwise
appropriate error message is sent
● The Web Page is displayed on the browser: After getting the response from
the server, the web browser displays the result

Types of Web Servers Softwares:

There are several types of web servers, each designed for specific purposes:
a. Apache HTTP Server : Apache is one of the most popular open-source web
servers globally, known for its flexibility and robustness. It’s highly
customizable and supports a wide range of modules and extensions.
b. Nginx : Nginx is another widely used web server known for its speed and
efficiency in handling concurrent connections.
c. Microsoft Internet Information Services (IIS) : IIS is a web server
developed by Microsoft for Windows servers. It’s commonly used for hosting
websites and web applications built on Microsoft technologies like ASP.NET.
d. LiteSpeed : LiteSpeed is a commercial web server known for its high
performance and security features. It’s often used in hosting environments
where speed and security are paramount.

Features of Web Servers

Web servers offer a range of features, including:


● Content Hosting : They store and serve web content, including HTML pages,
images, videos, and other multimedia files.
● Security : Web servers implement various security mechanisms to protect
against unauthorized access and cyberattacks.
● Load Balancing : Some web servers can distribute incoming traffic across
multiple server instances to ensure optimal performance and availability.
● Logging and Monitoring : They provide tools to track and analyze server
performance, user access, and error logs.
● Caching : Web servers can cache frequently accessed content to reduce server
load and improve response times.

Benefits of Web Servers

Using web servers offers several advantages, including:


● Scalability : Web servers can handle a large number of simultaneous
connections, making them suitable for high-traffic websites.
● Reliability : They are designed for continuous operation and can recover
from failures gracefully.
● Security : Web servers include security features to protect against common
web threats like DDoS attacks and SQL injection.
● Customization : Web server configurations can be tailored to specific
application requirements.

Uses of Web Server:

● Hosting Websites: The most common use of web servers is to host


websites, making them accessible on the internet.
● Web Applications: Web servers provide the infrastructure for hosting web
applications, enabling users to interact with software through a web
interface.
● File Sharing: Some web servers are used for file sharing and collaboration,
allowing users to upload and download files securely.
● Content Delivery: Content delivery networks (CDNs) use web servers to
distribute content like images and videos to users worldwide, reducing load
times.
● API Hosting: Web servers are used to host APIs (Application Programming
Interfaces) that allow applications to communicate and exchange data over
the internet.

1.2 Javascript in the Desktop with NodeJS

Create a Desktop App Using JavaScript

Building a desktop application with JavaScript is possible using various


frameworks and technologies. One popular approach is to use Electron, which is an
open-source framework developed by GitHub. Electron allows you to build cross-
platform desktop applications using web technologies such as HTML, CSS, and
JavaScript.

Steps to build a desktop app using JavaScript and Electron:

Step 1: Install Node.js and npm


Make sure you have Node.js and npm (Node Package Manager) installed on
your machine. You can download them from the official website: Node.js
Step 2: Create a new project:
Create a new directory for your project and navigate into it in the terminal.

mkdir my-electron-app
cd my-electron-app

Step 3: Initialize a new Node.js project


Run the following command to initialize a new package.json file.

npm init -y

Step 4: Install Electron


Install Electron as a development dependency using npm.

npm install electron --save-dev


Step 5: Create main and renderer processes:

In your project directory, create two files, main.js and index.html. main.js will be the
main process, and index.html will be the renderer process.

Example: This example shows the creation of a desktop app.

const { app, BrowserWindow } = require('electron');


let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 400,
height: 300,
webPreferences: {
nodeIntegration: true,
},
});
mainWindow.loadFile('index.html');

mainWindow.on('closed', function () {
mainWindow = null;
});
}
app.whenReady().then(createWindow);

app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit();
});

app.on('activate', function () {
if (mainWindow === null) createWindow();
});
Step 6: Update package.json:
Modify the scripts section in your package.json file to include a start script.
"scripts": {
"start": "electron main.js"
},

Step 7: Run your Electron app:


Execute the following command to run your Electron app.

npm start

This will launch your desktop application with Electron. You can further
customize and enhance your app by exploring the Electron API and integrating
additional packages as needed.

2.3 NPM

● NPM (Node Package Manager) is the default package manager for Node
and is written entirely in JavaScript.
● Developed by Isaac Z. Schlueter, it was initially released in January 12,
2010.
● NPM manages all the packages and modules for Node and consists of
command line client npm.
● NPM gets installed into the system with installation of Node.
● The required packages and modules in Node project are installed using
NPM.
● A package contains all the files needed for a module and modules are the
JavaScript libraries that can be included in Node project according to the
requirement of the project.
● NPM can install all the dependencies of a project through
the package.json file.
● It can also update and uninstall packages.
● In the package.json file, each dependency can specify a range of valid
versions using the semantic versioning scheme, allowing developers to
auto-update their packages while at the same time avoiding unwanted
breaking changes.

Some facts about NPM:

● At the time of writing this article, NPM has 580096 registered packages.
The average rate of growth of this number is 291/day which outraces
every other package registry.
● npm is open source
● The top npm packages in the decreasing order are: lodash, async, react,
request, express.
Installing NPM:
● To install NPM, it is required to install Node.js as NPM gets installed
with Node.js automatically.

Checking and updating npm version


● Version of npm installed on system can be checked using following
syntax:

Syntax to check npm version:

npm –v

If the installed version is not latest, one can always update it using the
given syntax:

Syntax to update npm version:

npm update npm@latest -g


As npm is a global package, -g flag is used to update it globally.
2.4 Serving files with the http module

The Built-in HTTP Module

Node.js has a built-in module called HTTP, which allows Node.js to transfer
data over the Hyper Text Transfer Protocol (HTTP).

To include the HTTP module, use the require() method:

var http = require('http');

Node.js as a Web Server

The HTTP module can create an HTTP server that listens to server ports and
gives a response back to the client.

Use the createServer() method to create an HTTP server:

Example :

var http = require('http');

//create a server object:


http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

The function passed into the http.createServer() method, will be executed


when someone tries to access the computer on port 8080.

Save the code above in a file called "demo_http.js", and initiate the file:

Initiate demo_http.js:

C:\Users\Your Name>node demo_http.js

If you have followed the same steps on your computer, you will see the same
result as the example: http://localhost:8080

Add an HTTP Header

If the response from the HTTP server is supposed to be displayed as HTML,


you should include an HTTP header with the correct content type:
Example :
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello World!');
res.end();
}).listen(8080);

The first argument of the res.writeHead() method is the status code, 200
means that all is OK, the second argument is an object containing the
response headers.

2.5 Introduction to the Express framework


● Express.js is a fast, flexible and minimalist web framework for Node.js.
● It’s effectively a tool that simplifies building web applications and APIs
using JavaScript on the server side.
● Express is an open-source that is developed and maintained by the
Node.js foundation.
● Express.js offers a robust set of features that enhance your productivity
and streamline your web application.
● It makes it easier to organize your application’s functionality with
middleware and routing.
● It adds helpful utilities to Node HTTP objects and facilitates the
rendering of dynamic HTTP objects.
● Express is a user-friendly framework that simplifies the development
process of Node applications.
● It uses JavaScript as a programming language and provides an efficient
way to build web applications and APIs.
● With Express, you can easily handle routes, requests, and responses,
which makes the process of creating robust and scalable applications
much easier.
● Moreover, it is a lightweight and flexible framework that is easy to learn
and comes loaded with middleware options.
● Whether you are a beginner or an experienced developer, Express is a
great choice for building your application.

Getting Started Express

1. Installation: Install Express using npm:

npm install express

2. Basic Example of an Express App:


const express = require('express');
const app = express();

// Define routes and middleware here


// ...

const PORT = process.env.PORT || 3000;


app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

● Import the ‘express’ module to create a web application using Node.js.


● Initialize an Express app using const app = express();.
● Add routes (endpoints) and middleware functions to handle requests and
perform tasks like authentication or logging.
● Specify a port (defaulting to 3000) for the server to listen on.

Key Features of Express

1. Middleware and Routing: Define clear pathways (routes) within your


application to handle incoming HTTP requests (GET, POST, PUT, DELETE)
with ease. Implement reusable functions (middleware) to intercept requests and
create responses, adding functionalities like authentication, logging, and data
parsing.
2. Minimalistic Design: Express.js follows a simple and minimalistic design
philosophy. This simplicity allows you to quickly set up a server, define routes,
and handle HTTP requests efficiently. It’s an excellent choice for building web
applications without unnecessary complexity.
3. Flexibility and Customization: Express.js doesn’t impose a strict
application architecture. You can structure your code according to your
preferences. Whether you’re building a RESTful API or a full-fledged web app,
Express.js adapts to your needs.
4. Templating Power: Incorporate templating engines like Jade or EJS to
generate dynamic HTML content, enhancing user experience.
5. Static File Serving: Effortlessly serve static files like images, CSS, and
JavaScript from a designated directory within your application.
6. Node.js Integration: Express.js seamlessly integrates with the core
functionalities of Node.js, allowing you to harness the power of asynchronous
programming and event-driven architecture.

Applications of Express
Express.js empowers you to construct a wide array of web applications. Here
are some captivating examples:

● RESTful APIs: Develop robust APIs that adhere to the REST


architectural style, enabling communication with other applications and
front-end interfaces.
● Real-time Applications: Leverage Express.js’s event-driven nature to
create real-time applications like chat or collaborative editing tools.
● Single-Page Applications (SPAs): Craft SPAs that fetch and update
content dynamically on the client-side, offering a seamless user
experience.

Unique features of Express JS

● Express.js is known for its simplicity and flexibility which comes with
various features that helps you to build efficient and scalable web
applications.
● It makes it easier to organize your application’s functionality with
middleware and routing.
● It adds helpful utilities to Node.js HTTP objects and facilitates the
rendering of dynamic HTTP objects.
1. Routing
● Routing is the process of handling an HTTP request that defines which
kind of response will be sent to the client on which particular request.
● In Node JS, we have a module called http to create a server, where we
create a server using http.createServer and pass a callback function
to http.createServer, where we get requests and responses as s parameter
and using if else and URL, we setup routes.

Node JS:

if (method === 'GET' && url === '/') {

res.end('Hello, World!');

While in Express JS, routing and creating servers is an inbuilt feature, we


don’t need to setup if else statements to setup routes. We can directly use the
simple methods of Express JS to setup routes.

Express JS:
app.get('/', (req, res) => { res.send('Hello, World!'); });

2. Middlewares
● Middlewares are the middle processes that execute between processes.
● In terms of web development, when we store passwords in a database
using a server, we use middleware to encrypt our passwords to make
them secure.
● But Node JS does not contain any middleware by default, but we can
create our own custom middleware in it.
● Instead of Node JS, Express.js contains built-in middleware
like express.static() to server static files to clients.

Syntax:

app.use(express.static('public'));

3. Error Handling
● Error handling is used to ensure the smooth running of your software
or program in case of any undetected issue in your software. But in
Node JS, there is no way to handle errors automatically through any
module.
● Developers can setup error handling using try catch blocks or event
emitters. But in Express JS, it is much easier to handle errors because
there are multiple ways to handle errors, like asynchronous handling,
global error handling, etc.

Syntax:
throw new Error('Error');

4. Request & Response Object

● Request and Response means what is requested by the client side and, in
exchange for that request, what data is sent to the client side from the
server side in terms of response.
● The request and response object is contained in both Node JS and Express
JS, but still, Express JS comes with multiple additional functionalities in
this object. For example, Express JS allows developers to use parameters
to access URLs, and res.send() is a much more convenient way to send
responses.
● It also allows user middlewares to be used in server-side coding.

Syntax:
app.get('/', (req, res) => {

console.log(req.method);

console.log(req.url);

res.send('Hello, World!');

});

5. Body Parsing
● Body parsing refers to parsing data sent from the client side to the server
side.
● The client sent data in the body of the request and also sent the type of
content in headers, so converting data according to the content type is
called body parsing. In Node.js, there is no built-in method or function to
parse client-side data, but we can use modules like querystring or buffer.
● Express JS contains built-in modules to parse data without any external
modules like middleware or Express. json() Parsing.

Syntax:

app.use(express.json());

Example

const express = require('express');


const app = express();
const port = 3000;
app.use(express.json());
app.use((req, res, next) => {
console.log(`MiddleWare Accepted`);
next();
});
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.post('/test', (req, res) => {
console.log(req.body);
res.send("Data Recieved!")
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
app.listen(port, () => {
console.log(`Server Established on Port -> ${port}`);
});

2.6 Server-side rendering with Templating Engines:

● Server-side rendering (SSR) is a popular technique for rendering a


normally client-side-only single-page app (SPA) on the server and then
sending a fully rendered page to the client.
● The client’s JavaScript bundle can then take over and the SPA can
operate as normal.
● SSR technique is helpful in situations where the client has a slow internet
connection and then rendering of the whole page on the client-side takes
too much time in certain situations Server Side Rendering might come as
handy.
● One of the widely used modules used to do Server Side Rendering in
Node.js is EJS Module.
● EJS stands for Embedded JavaScript template.

Feature of EJS Module:

● Use plain javascript.


● Fast Development time.
● Simple syntax.
● Faster execution.
● Easy Debugging.
● Active Development.

Installation of request module:

install express js and ejs using npm install.

npm install ejs

The require() method is used to load and cache JavaScript modules.

const ejs = require('ejs');


The next step is to create a folder and add a file name app.js and a file
named index.ejs. Be careful, about the syntax of the index file, here it is ejs
which denotes it is an ejs file. To run this file You need the following
command.

node app.js

Render file using EJS renderFIle() method

To perform Server Side Rendering we use renderFile() method of the ejs


module, which helps us to render the ejs file on the server side.

Syntax:

ejs.renderFile( fileName, { }, { }, callback);

Here, the callback function takes two arguments first is an error (if there is an
error that occurs then the renderfile returns an error), and on successful
rendering it returns a template.

Folder Structure:

Filename: app.js
Javascript

// Requiring modules
const express = require('express');
const app = express();
const ejs = require('ejs');
const fs = require('fs');
const port = 8000;

// Render index.ejs file


app.get('/', function (req, res) {

// Render page using renderFile method


ejs.renderFile('index.ejs', {},
{}, function (err, template) {
if (err) {
throw err;
} else {
res.end(template);
}
});
});

// Server setup
app.listen(port, function (error) {
if (error)
throw error;
else
console.log("Server is running");
});

Filename: index.ejs
HTML
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
</head>

<body>
<h1>Hello World</h1>
</body>

</html>

Steps to run the program:

Make sure you have installed the express and request module using the
following commands:
npm install express
npm install ejs
Run app.js using the below command:

node app.js

Now type localhost:8000 in your browser to display the ejs page to see the
below result:

2.7 Static Files


● Static files are files like images, CSS, and JavaScript files that do not
change dynamically.
● To serve static files we use the built-in middleware in node.js i.e.
express.static.
Example
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Common Types of Static Files
Images: JPG, PNG, GIF, SVG, etc.
CSS: Stylesheets that control the appearance of the web pages.
JavaScript: Scripts that add interactivity to the web pages.
Fonts: Web fonts like WOFF, TTF.
Documents: PDFs, Word documents, etc.
Usage in Web Development

● Performance: Serving static files from a Content Delivery Network


(CDN) or caching them improves load times.
● Organization: Typically, static files are organized in a dedicated
directory within a project, like /static or /assets.
● Security: Static files are generally safe to serve directly because they
don't contain sensitive data or require server-side processing

2.8 async/await

● In Node.js, async and await are syntactic sugars introduced in ES2017


(ECMAScript 2017) that simplify working with asynchronous code.
● Async/Await is a modern approach to asynchronous programming in
which you can write asynchronous code that looks and behaves like
synchronous code, making it easier to read and maintain.
● The "async" keyword is used to define a function as asynchronous, while
the "await" keyword is used to pause the execution of the function until a
promise is resolved.
● The "async" keyword is used to define a function as asynchronous. This
tells JavaScript that the function will perform asynchronous operations
and that it should return a Promise.
● Within the asynchronous function, you can use the "await" keyword to
pause the execution of the function until a Promise is resolved. This
makes the code look and behave like synchronous code, even though it's
asynchronous.
● When the Promise is resolved, the value it resolves with is returned by the
"await" keyword. This value can then be used in the next line of code.
● If the Promise is rejected, an error is thrown and can be caught with a
try/catch block.

Example for Async :


async function example()

return 'Hello, world!';

example().then(console.log); // Output: 'Hello, world!'

Example for Await :


async function getData()
{
const data = await fetch('https://api.example.com/data'); // fetch returns a
promise
return data.json(); // Assuming the response is in JSON format
}
getData().then(data => console.log(data)).catch(err => console.error(err));
Error Handling
Error handling with async/await is straightforward using try/catch blocks:
async function fetchData()
{
try
{
const response = await fetch('https://api.example.com/data');
if (!response.ok)
{
throw new Error('Network response was not ok');
}
const data = await response.json();
return data;
}
catch (error)
{
console.error('Error fetching data:', error);
}
}
fetchData();

2.9 Fetching JSON from Express.js

● The express. json() function is a built-in middleware function in


Express. It parses incoming requests with JSON payloads and is based on
body-parser.
● It's a critical component for handling JSON data in RESTful APIs and
web applications, allowing the server to automatically parse JSON data
from the request body.

Syntax:

express.json( [options] )

Parameters:

● The options parameter has various properties like inflate, limit, type, etc.

Return Value: It returns an Object.

Features
● Automatic Parsing: Automatically parses JSON data in the request body
and makes it available on req.body.
● Error Handling: If the JSON is malformed, express.json() throws a 400
Bad Request error, preventing the request from proceeding.
● Lightweight: Built directly into Express, eliminating the need for additional
packages to handle JSON parsing.
● Integration with Other Middleware: Can be used in conjunction with
other middleware like express.urlencoded() for handling different content
types.
Setting Up Express.js to Send JSON

1. Create an Express.js Server:

Install Express.js if you haven't already:

npm install express

2. Create a simple Express server that responds with JSON:

const express = require('express');

const app = express();

const port = 3000;

app.get('/api/data', (req, res) =>

const data = {

message: 'Hello, world!',

timestamp: new Date()

};

res.json(data); // Send JSON response

});

app.listen(port, () => {

console.log(`Server running at http://localhost:${port}`);

});
In this example, when a GET request is made to /api/data, the server responds with a JSON object.

3. Fetching JSON Data from the Client:

You can use various methods to fetch JSON data from an Express.js server on
the client side, including fetch, axios, or jQuery's $.ajax. Here’s how you can
use these methods:
● Using fetch API:

async function fetchData()


{
Try
{
const response = await fetch('http://localhost:3000/api/data');
if (!response.ok)
{
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data); // Process the JSON data here
}
catch (error)
{
console.error('Error fetching data:', error);
}
}
fetchData();

*** In Node.js, JSON (JavaScript Object Notation) is a lightweight data interchange format that's
used to store and exchange data. JSON is widely used because it's easy to read and write for
humans and easy to parse and generate for machines.
UNIT 3 ADVANCED NODE JS AND CONNECTION TO DATABASE
Introduction to NoSQL databases – MongoDB system overview - Basic
querying with MongoDB shell – Request body parsing in Express – NodeJS
MongoDB connection – Adding and retrieving data to MongoDB from NodeJS
– Handling SQL databases from NodeJS – Handling Cookies in NodeJS –
Handling User Authentication with NodeJS - CRUD operations with Node.js
and databases

3.3 Basic querying with MongoDB shell


● MongoDB Mongo shell is an interactive JavaScript interface that
allows you to interact with MongoDB instances through the command
line.
● The shell can be used for:
o Data manipulation
o Administrative operations such as maintenance of database
instances

● MongoDB Mongo shell is the default client for the MongoDB


database server.
● It’s a command-line interface (CLI), where the input and output are all
console-based.
● The Mongo shell is a good tool to manipulate small sets of data.

Here are the top features that Mongo shell offers:

● Run all MongoDB queries from the Mongo shell.


● Manipulate data and perform administration operations.
● Mongo shell uses JavaScript and a related API to issue commands.
● See previous commands in the mongo shell with up and down arrow
keys.
● View possible command completions using the tab button after partially
entering a command.
● Print error messages, so you know what went wrong with your
commands.

** MongoDB has recently introduced a new mongo shell known


as mongosh.

Installing the mongo shell


The mongo shell gets installed when you install the MongoDB server. It is installed in
the same location as the MongoDB server binary.

If you want to install it separately, you can visit the MongoDB download
center, from there select the version and package you need, download the
archive, and copy it to a location in your file system.
Mongo shell is available for all main operating systems, including:

● Windows
● Linux
● Mac OS

Connect to MongoDB database

Once you’ve downloaded and installed MongoDB, you can use the mongo
shell to connect with a MongoDB server that is up and running.

Note: It is required that your server is already running before you connect
with it through the shell. You can start the server in CMD using the
following command.
net start MongoDB
Then type mongo command to run the shell.
Mongo

Different port
The above mongo command only works if your MongoDB server
runs on the default port, which is 27017. If your MongoDB server runs on a
different port, you have to explicitly specify it in the command, as shown
below:
mongo --port 28010

Basic commands for Mongo shell


Run the db command to see the database you are currently working
with
db

Run the use command to switch to a different database. If you don’t


have a database,
use company

create collections and insert data with the following command:

● db refers to the current database in use.


● employee is the collection name.
● insertOne is the method to insert a document to the collection.

db.employee.insertOne( { name: "mark" } );


Use the find method to fetch data in a collection.
The forEach(printjson) method will print them with JSON formatting
db.employee.find().forEach(printjson)

Use the show dbs command to Show all databases


show dbs

Run the help command to get a list of help options available in the mongo
shell.
Help

To get a full list of commands that you can execute on the current
database, type db.help()
3.4 Request body parsing in Express
● Express is a lightweight and flexible routing framework
● That works on top of Node.js web server functionality to simplify its API
● Express is the most popular web framework for Node.js

Express body-parser is an npm module used to process data sent in an HTTP


request body. ( ** Node Package Manager)
● It provides four express middleware for parsing JSON, Text, URL-
encoded, and raw data sets over an HTTP request body.
● Before the target controller receives an incoming request, these
middleware routines handle it.

Body-parser
● Body-parser parses is an HTTP request body that usually helps
when you need to know more than just the URL being hit.
● Specifically in the context of a POST, PATCH, or PUT HTTP
request where the information you want is contained in the body.
● Using body-parser allows you to access req.body from within
routes and use that data.
● For example: To create a user in a database.
Installation
To install the body-parser first, you must create a project and the first command
you will write here is npm init -y.

This is used to create a JSON file, and in that you can add all the dependencies.

Step 1:

Step 2: Now, you have to install express for that, you will write a command
npm i express.

Step 3: After that, go ahead and install body-parser. For that write command on
your terminal.

Now, the body-parser is installed in your system.

Step 4: Go ahead and write a basic Express app that is common in every express
application.
Express Route-Specific
The example below shows you how to add body parsers - specifically to the
routes requiring them. This is the considered the most apt technique to utilize
body-parser with Express.

UNIT 4 RESTful APIs , Express.js and Testing


Designing RESTful APIs - Building RESTful APIs with Express.js -
Consuming APIs with Node.js
Testing - Writing unit tests with frameworks like Mocha and Chai - Debugging
techniques in Node.js- Code quality tools

UNIT 5 APP IMPLEMENTATION IN CLOUD


Cloud providers Overview – Virtual Private Cloud – Scaling (Horizontal and
Vertical) – Virtual Machines, Ethernet and Switches – Docker Container –
Kubernetes

Node JS
Express JS
Mongo DB

You tube link


https://www.youtube.com/watch?v=SdyzXQoQO18

You might also like