0% found this document useful (0 votes)
21 views94 pages

Unit1 RiteshKumarSingh

The document outlines a course on Web Development using the MERN stack, focusing on Node.js in Unit I. It includes details on the course objectives, outcomes, evaluation scheme, and prerequisites, along with a comprehensive syllabus covering topics such as Node.js installation, Express framework, advanced JavaScript, React.js, and MongoDB integration. The course aims to equip students with the skills to design and build dynamic web applications and understand server-side scripting and database connectivity.

Uploaded by

Amrish Sir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views94 pages

Unit1 RiteshKumarSingh

The document outlines a course on Web Development using the MERN stack, focusing on Node.js in Unit I. It includes details on the course objectives, outcomes, evaluation scheme, and prerequisites, along with a comprehensive syllabus covering topics such as Node.js installation, Express framework, advanced JavaScript, React.js, and MongoDB integration. The course aims to equip students with the skills to design and build dynamic web applications and understand server-side scripting and database connectivity.

Uploaded by

Amrish Sir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 94

Noida Institute of Engineering and Technology, Greater Noida

WEB DEVELOPMENT
USING MERN STACK

Unit: I

Introduction to Nodejs
Amarish Jaysawal
Course Details (Asst. Professor)
(B. Tech. 6th Sem)
CSE Department

28/05/2025 Ritesh Kumar Singh WEB DEVELOPMENT USING MERN STACK 1


Unit I
Faculty Introduction

Name Amarish Jaysawal


Highest Qualification M. Tech.
Designation Assistant Professor cum Trainer
Department Computer Science & Engineering
Total Experience 9.7 years
Subject Taught Web Development using MERN Stack, Web Development
using PHP, Laravel, Wordpress, MYSQL, SQL, MongoDB,
React, NodeJS,ExpressJS,Programming for Problem Solving
using C, Database Management System.

28/05/2025
Evaluation Scheme

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 3
Unit I
Syllabus

UNIT-I: Introduction to Nodejs

Installing Nodejs, Node in-built packages (buffer, fs, http, os,


path, util, url)Node.js modules, File System Module, Json data,
Http Server and Client, Error handling with appropriate HTTP,
Callback function, asynchronous programing REST API’s(GET,
POST PUT, DELETE UPDATE), Graph, Promises, Promise
Chaining, Introduction to template engine (EJS).

28/05/2025 4
Syllabus

UNIT-II: Express Framework

Configuring Express, Postman configuration, Environment


Variables, Routing, Defining pug templates, HTTP method of
Express, URL binding, middleware function, Serving static files,
Express sessions, REST full API’s, FORM data in Express, document
modeling with Mongoose.

28/05/2025 5
Syllabus

UNIT-III: Advance Javascript before React js

Advance JavaScript, ECMASCRIPT Version ES-6,ES-7,ES-8,


Functions Function as types Optional and default parameters,
Arrow functions, Function overloading, Getters and setters,
class, Error Handling, Promise, Async/Await, map() vs forEach(),
DOM, Manipulation,Inheritance,Polymorphism,Encapsulation,
static, classes,Module System Import and Export modules.

28/05/2025 6
Syllabus

UNIT-IV: Building Single Page App with React js

Virtual DOM, JSX Expressions, Component, Tables, ReactJS Forms


and Forms validation.

28/05/2025 7
Syllabus

UNIT-V: Connecting React js with MongoDB

Environment Setup of Mongo dB , data modeling ,The current


SQL/NoSQL landscape, Create collection in Mongo dB, CRUD
Operations in MongoDB. Mongo's feature set, Introduction to
Mongoose, understanding mongoose schemas and datatypes,
Connecting React with mongo dB using API.

28/05/2025 8
Branch Wise Application

1. Real time web analytics


2. Digital Advertising
3. E-Commerce
4. Publishing
5. Massively Multiplayer Online Games
6. Backend Services and Messaging
7. Project Management & Collaboration
8. Real time Monitoring Services
9.Live Charting and Graphing
10. Group and Private Chat

28/05/2025 9
Course Objective

In this semester, the students will

Study how to design and build static as well as dynamic webpages and
interactive web applications

Students examine advanced topics like ReactJS, NodeJS, MongoDB for web
applications.

Also examine Express framework for interactive web applications that use rich
user interfaces .

28/05/2025 10
Course Outcomes (COs)

At the end of course, the student will be able to:


CO1 : Explain, analyze and apply the role of server-side scripting language like Nodejs .

CO2 : Demonstrate Express framework to design and implement dynamic web pages .

CO3 : Apply the knowledge of Javascript that are vital in understanding ReactJS.

CO4 : Analyze build and develop single page application using client-side programming.

CO5 : Understand the impact of web designing by database connectivity with Mongodb

28/05/2025 11
Program Outcomes (POs)

Engineering Graduates will be able to:

PO1 : Engineering Knowledge

PO2 : Problem Analysis

PO3 : Design/Development of solutions

PO4 : Conduct Investigations of complex problems

PO5 : Modern tool usage

PO6 : The engineer and society


28/05/2025 12
Program Outcomes (POs)

Engineering Graduates will be able to:

PO7 : Environment and sustainability

PO8 : Ethics

PO9 : Individual and teamwork

PO10 : Communication

PO11 : Project management and finance

PO12 : Life-long learning


28/05/2025 13
COs - POs Mapping

CO.K PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

CO1 2 2 2 3 3 - - - - - - -

CO2 3 2 3 2 3 - - - - - - -

CO3 3 2 3 2 3 - - - - - - -

CO4 3 2 3 2 3 - - - - - - -

CO5 3 2 3 3 3 - - - - - - -

AVG 2.8 2.0 2.8 2.4 3.0 - - - - - - -

28/05/2025 14
Program Specific Outcomes(PSOs)
Program Specific
S. No. PSO Description
Outcomes (PSO)
Understand to shows relationships and
interactions between classes or objects of a
1 PSO1 pattern.

Study to speed up the development process by


2 PSO2 providing well-tested, proven development

Select a specific design pattern for the solution of a


3 PSO3 given design problem

Create a catalogue entry for a simple design


pattern whose purpose and application is
4 PSO4 understood.

28/05/2025 15
COs - PSOs Mapping

CO.K PSO1 PSO2 PSO3 PSO4

CO1 3 - - -

CO2 3 3 - -

CO3 3 3 - -

CO4 3 3 - -

CO5 3 3 - -

28/05/2025 16
Program Educational Objectives (PEOs)

Program Educational
PEOs Description
Objectives (PEOs)
To have an excellent scientific and engineering breadth so as to comprehend,
PEOs analyze, design and provide sustainable solutions for real-life problems using state-
of-the-art technologies.

To have a successful career in industries, to pursue higher studies or to support


PEOs entrepreneurial endeavors and to face the global challenges.

To have an effective communication skills, professional attitude, ethical values and a


PEOs desire to learn specific knowledge in emerging trends, technologies for research,
innovation and product development and contribution to society.

To have life-long learning for up-skilling and re-skilling for successful professional
PEOs career as engineer, scientist, entrepreneur and bureaucrat for betterment of society.

28/05/2025 17
Result Analysis(Department Result & Subject Result & Individual result

Name of the faculty Subject code Result % of clear passed

Mr. Amarish
ACSE0614
Jaysawal

28/05/2025 18
Pattern of Online External Exam Question Paper (100 marks)

28/05/2025 19
Pattern of Online External Exam Question Paper (100 marks)

28/05/2025 20
Pattern of Online External Exam Question Paper (100 marks)

28/05/2025 21
Pattern of Online External Exam Question Paper (100 marks)

28/05/2025 22
Pattern of Online External Exam Question Paper (100 marks)

28/05/2025 23
Prerequisite / Recap

Student should have knowledge of Web technology and

terminology.

Knowledge of HTML ,CSS and Java Script required .

knowledge of Programing language such as C/C++ etc.

Good problem solving Skill .

28/05/2025 24
Brief Introduction about the Subject with videos

YouTube /Other Video Links

• https://youtu.be/BLl32FvcdVM

• https://youtu.be/v9ejT8FO-7I?list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc

28/05/2025 25
Unit I Content

Installing Nodejs, Node in-built packages


(buffer, fs, http, os, path, url)
Node.js modules, File System Module, Json
data, Http Server and Client,
Error handling with appropriate HTTP, Callback
function,synchronous
programing,asynchronous programing
REST API’s(GET, POST PUT, DELETE UPDATE),
Promises, Introduction to template engine
(EJS).
28/05/2025 26
Unit I Objective

In Unit I, the students will be able to find


Definitions of terms and concepts.
The idea of installation of node js.
How to handling Error handling with appropriate HTTP,
What is Callback function, asynchronous programing
Scope of development activity: applications, toolkits,
frameworks.
Promise Chaining, Introduction to template engine (EJS)
etc.

28/05/2025 27
Topic Objective

Topic : Installing Nodejs, Node in-built packages (buffer, fs,


http, os,
path, util, url)

In this topic, the students will gain , how to install Nodejs ,


what are the built in packages used in the nodejs and many
more.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 28
Unit I
Node Js - Overview

 Node.js is an open-source, cross-platform JavaScript runtime environment


and library for running web applications outside the client's browser. Ryan
Dahl developed it in 2009, and its latest iteration, version 15.14, was
released in April 2021.

 Developers use Node.js to create server-side web applications, and it is


perfect for data-intensive applications since it uses an asynchronous,
event-driven model.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 29
Unit I
Node Js– Overview Cont………

Why Do We Use Node Js

Node Js is built on Google Chrome’s V8 engine, and for this reason its execution time is
very fast and it runs very quickly.
There are more than 50,000 bundles available in the Node Package Manager and for
that reason developers can import any of the packages any time according to their
needed functionality for which a lot of time is saved.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 30
Unit I
Node Js – Overview Cont………

As Node Js do not need to wait for an API to return data , so for building
real time and data intensive web applications, it is very useful. It is totally
asynchronous in nature that means it is totally non-blocking.
The loading time for an audio or video is reduced by NodeJs because there
is better synchronization of the code between the client and server for
having the same code base.
As NodeJs is open-source and it is nothing but a JavaScript framework , so
for the developers who are already used to JavaScript, for them starting
developing their projects with NodeJs is very easy.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 31
Unit I
Node Js – Features

Features of Node Js
Asynchronous in Nature and Event driven: The servers made with
the NodeJs never waits for the from an API. Without waiting for
the data from the API, it directly moves to the next API. So all the
APIs of NodeJS are totally non-blocking in nature. In order to
receive and track all the responses of the previous API requests, it
follows an event driven mechanism. Hence we can say that all the
NodeJs API are non-blocking in nature.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 32
Unit I
Node Js – feature continue………

Single Threaded Architecture: With event looping, a single threaded


architecture is followed by NodeJs and for this architecture makes Node Js
more scalable. In contrast to other servers, limited threads are created by
them for processing the requests. Whereas for the event driven mechanism,
the NodeJS servers reply in a non-blocking or an asynchronous manner and
for this reason NodeJS becomes more scalable. If we compare Node Js with
other traditional servers like Apache HTTP servers, then we can say Node Js
handles a larger number of requests. A single threaded program is followed
by NodeJS and this allows NodeJs to process a huge amount of requests.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 33
Unit I
Node Js – Feature Cont………

Scalable: Nowadays, scalable software is demanded by most of the companies. One of


the most pressing concerns in Software Development is addressed by NodeJs and that is
scalability. Concurrent requests can be handled very efficiently using NodeJs. A cluster
module is used by NodeJs for managing the load balancing for all the active CPU cores. The
most appealing feature of NodeJs is that it can partition the applications horizontally and
this partition procedure is mainly achieved by it due to the use of child processes.
Quick Execution time for code: V8 JavaScript runtime motor is used by NodeJs and
this is also used by Google chrome. A wrapper is provided for the JavaScript by the hub
and for that reason the runtime motor becomes faster and for this reason inside NodeJs,
the preposition process of the requests also become faster.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 34
Unit I
Node Js– Feature Cont………

Compatibility on the cross platforms: Different types of systems like Windows, UNIX,
LINUX, MacOS and other mobile devices can use NodeJs.
Fast Data Streaming: The processing time of the data that have been transmitted to
different streams takes a long time. Whereas for processing the data, NodeJs takes a very
short amount of time and it does it at a very fast rate. NodeJs saves a lot of time because
the files are processed and uploaded simultaneously by NodeJs. So as a result, the overall
speed of data and video streaming is improved by NodeJs.
No Buffering : The data is never buffered in NodeJs application.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 35
Unit I
Node Js – Installation

Step 1: Download the Installer


Download the Windows Installer from NodeJs official website. Make sure you have
downloaded the latest version of NodeJs. It includes the NPM package manager.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 36
Unit I
Node Js – Installation Cont………

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 37
Unit I
Node Js – Installation Cont…..
Step 2: Install Node.js and NPM
After choosing the path, double-click to install .msi binary files to
initiate the installation process. Then give access to run the
application.
You will get a welcome message on your screen and click the “Next”
button. The installation process will start.

Choose the desired path where you want to install Node.js.


By clicking on the Next button, you will get a custom page setup on
the screen. Make sure you choose npm package manager , not the
default of Node.js runtime . This way, we can install Node and NPM
simultaneously.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 38
Unit I
Node Js- Installation cont….

The setup is ready to install Node and NPM. Let’s click on


the Install button .

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 39
Unit I
Node in-build packages

Node.js has a set of built-in modules which you can use


without any further installation.
Here is a list of the built-in modules of Node.js version
6.10.3:

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 40
Unit I
Node in-build packages

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 41
Unit I
Node in-build packages

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 42
Unit I
Node in-build packages

28/05/2025 Ritesh Kumar Singh WEB DEVELOPMENT USING MEAN STACK 43


Unit I
Node Js Modules

What is a Module in Node.js


Consider modules to be the same as JavaScript libraries.
A set of functions you want to include in your application.
Built-in Modules
Node.js has a set of built-in modules which you can use
without any further installation.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 44
Unit I
Node Js Modules
Include Modules
To include a module, use the require() function with the
name of the module:
var http = require('http');
Now your application has access to the HTTP module, and
is able to create a server:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 45
Unit I
Node Js Modules
Node.js File System Module
Node.js as a File Server
The Node.js file system module allows you to work with the file
system on your computer.
To include the File System module, use the require() method:
var fs = require('fs');
Common use for the File System module:
Read files
Create files
Update files
Delete files
Rename files

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 46
Unit I
Node Js Modules

Read Files
The fs.readFile() method is used to read files on your
computer.
Assume we have the following HTML file (located in the same
folder as Node.js):
demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
Ritesh Kumar Singh WEB
28/05/2025 DEVELOPMENT USING MEAN STACK 47
Unit I
Node Js Modules
Create a Node.js file that reads the HTML file, and return
the content:
Example
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
Ritesh Kumar Singh WEB
28/05/2025 DEVELOPMENT USING MEAN STACK 48
Unit I
Node Js Modules

Ceate Files
The File System module has The fs.appendFile() method appends specified content to a
methods for creating new file. If the file does not exist, the file will be created:
files: Example
•fs.appendFile() Create a new file using the appendFile() method:
var fs = require('fs');
•fs.open()
•fs.writeFile() fs.appendFile('mynewfile1.txt', 'Hello
content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
Run example »

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 49
Unit I
JSON Data

How to read and write JSON file using Node.js


Node.js is an open source and cross-platform runtime environment for
executing JavaScript code outside of the browser. It is widely used in
developing APIs and microservices from small to large companies.

JSON or JavaScript Object Notation is a light weight, text-based data


interchange format. Like XML, it is one of the way of exchanging information
between applications. This format of data is widely used by web
applications/APIs to communicate with each other.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 50
Unit I
JSON Data

Reading a JSON file:


Method 1: Using require method: The simplest method to read a JSON file is
to require it in a node.js file using require() method.
 Syntax:
const data = require('path/to/file/filename');
Example: Create a users.json file in the same directory where index.js file
present. Add following data to the json file.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 51
Unit I
JSON Data

[
{
"name": "John",
"age": 21,
"language": ["JavaScript", "PHP", "Python"]
},
{
"name": "Smith",
"age": 25,
"language": ["PHP", "Go", "JavaScript"]
}
]

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 52
Unit I
JSON Data
Method 2: Using the fs module: We can also use node.js fs module to read a
file. The fs module returns a file content in string format so we need to
convert it into JSON format by using JSON.parse() in-built method.
Add the following code into your index.js file:
index.js file:

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 53
Unit I
JSON Data

const fs = require("fs");

// Read users.json file


fs.readFile("users.json", function(err, data) {

// Check for errors


if (err) throw err;

// Converting to JSON
const users = JSON.parse(data);

console.log(users); // Print users


});

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 54
Unit I
JSON Data
Writing to a JSON file: We can write data into a JSON file by using the
node.js fs module. We can use writeFile method to write data into a file.
Syntax:
fs.writeFile("filename", data, callback);
Example: We will add a new user to the existing JSON file, we have created
in the previous example. This task will be completed in three steps:
Read the file using one of the above methods.
Add the data using .push() method.
Write the new data to the file using JSON.stringify() method to convert
data into string.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 55
Unit I
JSON Data
const fs = require("fs");

// STEP 1: Reading JSON file


const users = require("./users");

// Defining new user


let user = {
name: "New User",
age: 30,
language: ["PHP", "Go", "JavaScript"]
};

// STEP 2: Adding new data to users object


users.push(user);

// STEP 3: Writing to a file


fs.writeFile("users.json", JSON.stringify(users), err => {

// Checking for errors


if (err) throw err;

console.log("Done writing"); // Success


}); Ritesh Kumar Singh WEB
28/05/2025 DEVELOPMENT USING MEAN STACK 56
Unit I
HTTP
An overview of HTTP
HTTP is a protocol for fetching resources such as HTML documents. It is the
foundation of any data exchange on the Web and it is a client-server
protocol, which means requests are initiated by the recipient, usually the
Web browser. A complete document is reconstructed from the different sub-
documents fetched, for instance, text, layout description, images, videos,
scripts, and more.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 57
Unit I
HTTP

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');

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 58
Unit I
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
}).listen(8080); //the server object listens on port 8080

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 59
Unit I
Callback function

A callback is a function which is called when a task is completed, thus helps in


preventing any kind of blocking and a callback function allows other code to run in
the meantime.
Callback is called when task get completed and is asynchronous equivalent for a
function.
Using Callback concept, Node.js can process a large number of requests without
waiting for any function to return the result which makes Node.js highly scalable.
For example: In Node.js, when a function start reading file, it returns the control
to execution environment immediately so that the next instruction can be
executed. Once file I/O gets completed, callback function will get called to avoid
blocking or wait for File I/O.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 60
Unit I
Callback function

Example 1: Code for reading a file synchronously (blocking code) in


Node.js. Create a text file inputfile1.txt with the following content:
Hello Programmer!!! Learn NodeJS with GeeksforGeeks
// Write JavaScript code
var fs = require("fs");
var filedata = fs.readFileSync('inputfile1.txt');
console.log(filedata.toString());
console.log("End of Program execution");

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 61
Unit I
Callback function

Explanation: fs library is loaded to handle file-system


related operations. The readFileSync() function is
synchronous and blocks execution until finished. The
function blocks the program until it reads the file and
then only it proceeds to end the program.

Output:

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 62
Unit I
Callback function

Example 2: Code for reading a file asynchronously (non-blocking code) in Node.js. Create a text
file inputfile1.txt with the following content.
Hello Programmer!!! Learn NodeJS with GeeksforGeeks
// Write a JavaScript code
var fs = require("fs");

fs.readFile('inputfile1.txt', function (ferr, filedata) {


if (ferr) return console.error(ferr);
console.log(filedata.toString());
});
console.log("End of Program execution");

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 63
Unit I
Callback function
Explanation: fs library is loaded to handle file-system related operations. The
readFile() function is asynchronous and control return immediately to the
next instruction in the program while the function keep running in the
background. A callback function is passed which gets called when the task
running in the background are finished.
Output:

28/05/2025 Ritesh Kumar Singh WEB DEVELOPMENT USING MEAN STACK 64


Unit I
REST API
Representational State Transfer (REST) is an architectural style that defines
a set of constraints to be used for creating web services. REST API is a way of
accessing web services in a simple and flexible way without having any
processing.
REST technology is generally preferred to the more robust Simple Object
Access Protocol (SOAP) technology because REST uses less bandwidth, simple
and flexible making it more suitable for internet usage. It’s used to fetch or
give some information from a web service. All communication done via REST
API uses only HTTP request.

28/05/2025 Ritesh Kumar Singh WEB DEVELOPMENT USING MEAN STACK 65


Unit I
REST API
Working: A request is sent from client to server in the form of a web URL as
HTTP GET or POST or PUT or DELETE request. After that, a response comes
back from the server in the form of a resource which can be anything like
HTML, XML, Image, or JSON. But now JSON is the most popular format being
used in Web Services.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 66
Unit I
REST API
In HTTP there are five methods that are commonly used in a REST-based Architecture
i.e., POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and
delete (or CRUD) operations respectively. There are other methods which are less
frequently used like OPTIONS and HEAD.
GET: The HTTP GET method is used to read (or retrieve) a representation of a resource.
In the safe path, GET returns a representation in XML or JSON and an HTTP response code
of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD
REQUEST).

POST: The POST verb is most often utilized to create new resources. In particular, it’s
used to create subordinate resources. That is, subordinate to some other (e.g. parent)
resource. On successful creation, return HTTP status 201, returning a Location header with
a link to the newly-created resource with the 201 HTTP status.

28/05/2025 Ritesh Kumar Singh WEB DEVELOPMENT USING MEAN STACK 67


Unit I
REST API
PUT: It is used for updating the capabilities. However, PUT can also be used to create a
resource in the case where the resource ID is chosen by the client instead of by the server.
In other words, if the PUT is to a URI that contains the value of a non-existent resource ID.
PATCH: It is used to modify capabilities. The PATCH request only needs to contain the
changes to the resource, not the complete resource. This resembles PUT, but the body
contains a set of instructions describing how a resource currently residing on the server
should be modified to produce a new version.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 68
Unit I
REST API
Request and Response
Now we will see how request and response work for different HTTP methods.
Let’s assume we have
an API(https://www.geeksforgeeks.org/api/students) for all students data of
gfg.
GET: Request for all Students.
RequestGET:/api/studentsPOST: Request for Posting/Creating/Inserting
Data
Request
POST:/api/students
{“name”:”Raj”}

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 69
Unit I
GraphQL
 GraphQL is a query language for your API, and a server-side runtime for
executing queries using a type system you define for your data. GraphQL
isn't tied to any specific database or storage engine and is instead backed
by your existing code and data.
 GraphQL is a query language for your API, and a server-side runtime for
executing queries using a type system you define for your data. GraphQL
isn't tied to any specific database or storage engine and is instead backed
by your existing code and data.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 70
Unit I
GraphQL
Why GraphQL
RESTful APIs follow clear and well-structured resource-oriented approach. However, when
the data gets more complex, the routes get longer. Sometimes it is not possible to fetch
data with a single request. This is where GraphQL comes handy. GraphQL structures data
in the form of a graph with its powerful query syntax for traversing, retrieving, and
modifying data.

The following are advantages of using GraphQL query Language −


Ask for what you want − and get it
Send a GraphQL query to your API and get exactly what you need. GraphQL queries always
return predictable results. Applications using GraphQL are fast and stable. Unlike Restful
services, these applications can restrict data that should be fetched from the server.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 71
Unit I
Promises in Node.js

Introduction: Callback functions are used for Asynchronous events.


Whenever any asynchronous event has to take place it is generally
preferred to use callbacks (if data is not nested or inter-dependent).

What are Promises A promise is an advancement of callbacks in Node.


In other words, a promise is a JavaScript object which is used to handle
all the asynchronous data operations. While developing an application you
may encounter that you are using a lot of nested callback functions.

Ritesh Kumar Singh


28/05/2025 WEB DEVELOPMENT USING MEAN STACK 72
Unit I
Promises in Node.js

dboper.insertDocument(db, { name: "Test", description: "Test"},


"test", (result) => {
console.log("Insert Document:\n", result.ops);

dboper.findDocuments(db, "test", (docs) => {


console.log("Found Documents:\n", docs);

dboper.updateDocument(db, { name: "Test" },


{ description: "Updated Test" }, "test",

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 73
Unit I
Promises in Node.js
(result) => {
console.log("Updated Document:\n", result.result);

dboper.findDocuments(db, "test", (docs) => {


console.log("Found Updated Documents:\n", docs);

db.dropCollection("test", (result) => {


console.log("Dropped Collection: ", result);

client.close();
});
});
});
});
});

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 74
Unit I
Promises in Node.js
This is what happens due to the nesting of callback functions. Now imagine if
you need to perform multiple nested operations like this. That would make your
code messy and very complex. In Node.js world, this problem is
called “Callback Hell”.

To resolve this issue we need to get rid of the callback functions whilst
nesting. This is where Promises come into the picture. A Promise in Node
means an action which will either be completed or rejected. In case of
completion, the promise is kept and otherwise, the promise is broken. So as the
word suggests either the promise is kept or it is broken. And unlike callbacks,
promises can be chained.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 75
Unit I
Promises in Node.js
Callbacks to Promises Promises notify whether the request is fulfilled or
rejected. Callbacks can be registered with the .then() to handle fulfillment
and rejection. The .then() can be chained to handle the fulfillment and
rejection whereas .catch() can be used for handling the errors(if any).
dboper.insertDocument(db,
{ name: "Test", description: "Just a test"},
"test").then((result) => {
console.log("Insert Document:\n", result.ops);
});

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 76
Unit I
Promises in Node.js

Nested Promises: Often you will encounter situations where you need to
make use of nested Promises. Nested promises begin with a .then() and in
each of the .then() we have a return statement. After the return
statement, .then() follows in the same manner. Following example shows
the worst case scenario wherein multiple .then() methods are used in order
to declare nested promises (which are dependent on each other for their own
execution).

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 77
Unit I
Node.js Promise Chaining

Promise chaining: Promise chaining is a syntax that allows you to chain


together multiple asynchronous tasks in a specific order. This is great for
complex code where one asynchronous task needs to be performed after the
completion of a different asynchronous task.
To demonstrate promise chaining, the following function will be used to
simulate an asynchronous task. In reality, it’s just adding up a couple of
numbers, waiting two seconds, and fulfilling the promise with the sum.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 78
Unit I
Node.js Promise Chaining

const add = (a, b) => {


return new Promise((resolve, reject) => {
setTimeout(() => {
if (a < 0 || b < 0) {
return reject('Numbers must be non-negative')
}
resolve(a + b)
}, 2000)
})
}

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 79
Unit I
Node.js Promise Chaining

add(1, 2).then((sum) => {


console.log(sum) // Print 3
return add(sum, 4)
}).then((sum2) => {
console.log(sum2) // Print 7
}).catch((e) => {
console.log(e)
});

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 80
Unit I
Template engines

Template engines are used when you want to rapidly build web
applications that are split into different components. Templates also enable
fast rendering of the server-side data that needs to be passed to the
application.

Template engines are mostly used for server-side applications that are run
on only one server and are not built as APIs. The popular ones include Ejs,
Jade, Pug, Mustache, HandlebarsJS, Jinja2, and Blade.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 81
Unit I
Daily Quiz
Q 1 -. Which of the following statements are true?
A Node.js is a server side language.
B Node.js is a client side language.
C Node.js is a both server and client side language.
D None of the above.

Q2-) Node.js is written in which language?


A -C
B –C++
C -Java
D -JavaScript

Q 3 - Which of the following are examples of node modules?


Express
Body-parser
Socket.io
All of the above

28/05/2025 Ritesh Kumar Singh WEB DEVELOPMENT USING MEAN STACK 82


Unit I
Daily Quiz

Q 4 -) To include the HTTP server in the node module, what function do we use?
A get()
B require()
C createServer()
D None of the above

Q5-) To include the HTTP server in the node module, what function do we use?
A Export
B Expose
C Require
D None of the above

Q 6 -) Default scope in Node.js application is?


A Global
B Local
C Local to objects
D None of the above Ritesh Kumar Singh WEB
28/05/2025 DEVELOPMENT USING MEAN STACK 83
Unit I
Weekly Assignment

1. What is Node.Js.
2. What is the various module present in Node.Js.
3. Describe the steps to install Node.Js in windows.
4. Elaborate promises in Node.Js.
5. Discuss Callback function in Node.Js.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 84
Unit I
Previous Year Question paper

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 85
Unit I
Previous Year Question paper(Contd…)

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 86
Unit I
Topic Link ( YouTube & NPTEL Video Links)

YouTube /other Video Links

• https://youtu.be/rI4kdGLaUiQ?list=PL6n9fhu94yhUbctIoxoVTrklN3LMwTCmd

• https://youtu.be/v9ejT8FO-7I?list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc

• https://youtu.be/VGLjQuEQgkI?list=PLt4nG7RVVk1h9lxOYSOGI9pcP3I5oblbx

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 87
Unit I
MCQ (End of Unit)

1 Which of the following is true about package.json?


 package.json is present in the root directory of any Node application/module.
 package.json is used to define the properties of a package.
 package.json can be used to update dependencies of a Node application.
All of the above.

2. Which of the following is true about writable stream?


 writable stream is used for write operation.
 Output of readable stream can be input to a writable stream.
 Both of the above.
 None of the above.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 88
Unit I
MCQ (End of Unit)

3. Which of the following is true about fs module of Node?


 Every method in fs module have synchronous as well as asynchronous form.
 Asynchronous methods of fs module take last parameter as completion function callback and first
parameter of the callback function as error.
 Both of the above.
 None of the above.

4. Which method of fs module is used to delete a file?

 fs.delete(fd, len, callback)


fs.remove(fd, len, callback)
fs.unlink(path, callback)
None of the above.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 89
Unit I
Glossary Questions
Top 10 Node.Js interview questions

1. How NodeJs works for server side?


2. How is Node.Js useful for the client and server side programming?
3. Explain the benefits of Node.Js.
4. Describe the file module in Node.Js.
5. Discuss the various module in Node.Js.
6. What is callback function in Node.Js?
7. What is GraphQL?
8. What is Promise Chaining?
9. Describe the significance of promises in Node.Js.
10.What are Template engine?
28/05/2025 Ritesh Kumar Singh WEB DEVELOPMENT USING MEAN STACK 90
Unit I
Expected Questions for University Exam
1. How NodeJs works for server side?
2. How is Node.Js useful for the client and server side programming?
3. Explain the benefits of Node.Js.
4. Describe the file module in Node.Js.
5. Discuss the various module in Node.Js.
6. What is callback function in Node.Js?
7. What is GraphQL?
8. What is Promise Chaining?
9. Describe the significance of promises in Node.Js.
10.What are Template engine?

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 91
Unit I
Summary
Till Now we understand, How to Install Node.js and NPM on Windows and Mac.
Smalltalk MVC, what are the model ,view and controller defined by small talk,
design pattern in The catalog, we learn how to organized the catalog, learn how
to solve real world problems with design patterns, what are the approaches and
Patterns that help in real world problem , how to choose best pattern and what
are uses of the patterns.
The Principle of Least knowledge, also known as The law of Demeter, or more
precisely, the Law of Demeter for Functions/Methods (LoD-F) is a design principle
which provides guidelines for designing a system with minimal dependencies.

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 92
Unit I
References
1. Simon Holmes, Clive Herber, “Getting MEAN with Mongo, Express,
Angular, and Node”, 2nd Edition 2016, Addison Wesley Publication.
2. Dhruti Shah, “Comprehensive guide to learn Node.js”, 1st Edition, 2018
BPB Publications.
3. Christoffer,Noring,Pablo,Deeleman,“Learning Angular”,3rd Edition,2017
Packt publications. .
4. Peter Membrey, David Hows, Eelco Plugge, “MongoDB Basics”, 2nd
edition, 2018, International Publication.
5. Christoffer
28/05/2025
Noring, Pablo Deeleman,WEB“Learning
Ritesh Kumar Singh
Angular”,3rd Edition,93
DEVELOPMENT USING MEAN STACK
Unit I
THANK YOU

Ritesh Kumar Singh WEB


28/05/2025 DEVELOPMENT USING MEAN STACK 94
Unit I

You might also like