0% found this document useful (0 votes)
290 views232 pages

FSWD Sem 5

Full stack

Uploaded by

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

FSWD Sem 5

Full stack

Uploaded by

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

FULL STACK WEB DEVELOPMENT

:
Subject Code IT3501

Semester -V (Informaion Technology)

© Copyright with Author


Allpublishing rights (printed and ebook version)
reserved with Technical Publications. No port of this book
should be reproduced in ony form, Electronic, Mechanical, Photocopy or any
information storage and
retrieval system without prior permission in writing, from Technical Publications, Pune.

Published by :

TECHNICAL' Amit Residency,Ofice No.l, 412, Shaniwar Peth,


PUBLICATIONS Pune - 411030, M.S. INDIA, Ph.: +91-020-24495496/97
SINCE 1993 An Up-Thrust lor Knowiedge Email : info@technicalpublications. in Website : www.technicalpublications.in

Printer :

Yogiraj Printers & Binders


Sr.No. 10/1A,
Ghule Industrial Estate, Nanded Village Road,
Tal. - Haveli, Dist. Pune -
411041.

ISBN 978-93-5585-395-0

gl7893 55 ls53950 AU 21

9789355853950 [1)
(i)
PREFACE
The importance of Full Stack Web Development is well known in various
engineering fields. Overwhelming response to my books on various subjects
inspired me to write this book. The book is structured to cover the key aspects of
the subject FullStack Web Development.
The book uses plain, lucid language to explain fundamentals of this subject.
The book provides logical method of explaining various complicated concepts and
stepwise methods to explain the important topics. Each chapter is well supported
with necessary ilustrations. practical examples and solved problems. AII the
chapters in the book are arranged in a proper sequence that permits each topic to
build upon earlier studies. All care has been taken to make students comnfortable in
understanding the basic concepts of the subject.
Representative questions have been added at the end of section to help the
students in picking important points from that section.
The book not only covers the entire scope of the subject but explains the
philosophy of the subject. This makes the understanding of this subject more clear
and makes it more interesting. The book will be very useful not only to the students
but also to the subject teachers. The students have to omit nothing and possibly
have to cover nothing more.
I wish to express my profound thanks to all those vho helped in making this
book a reality. Much needed moral support and encouragement is provided on
numerous occasions by my whole family. I wish to thank the Publisher and the
entire team of Technical Publications who have taken immense pain to get this
book in time with quality printing.
Any suggestion for the improvement of the book will be acknowledged and
well appreciated.

Author
Mrs. A. A. Puntambekas

Dedicateò toGod.

(ii)
SYLLABUS
Full Stack Web Development - (1T3501)
UNIT I BASICS OF FULL STACK
Understanding the Basic Web Development Framework - User- Browser - Webserver - Backend
Services - MVCArchitecture - Understanding the differecnt stacks -The role of Express - Angular
-
Node - Mongo DB - React. (Chapter - 1)

UNIT II NODE JS
Basics of Node JS - Installation - Working with Node packages -Using Node package manager -
Creating a simple Node.js application -Using Events-Listeners - Timers- Callbacks - Handling
Data V/O - Implementing HTTP services in Node.js. (Chapter - 2)

UNIT II MONGO DB
Understanding NoSQL and MongoDB - Building MongoDB Environment - User accounts -
Access control - Administering databases - Managing collections - Connecting to MongoDB from
Node.js - simple applications. (Chapter - 3)

UNIT IV EXPRESS AND ANGULAR


Implementing Express in Node.js - Configuring routes - Using Request and Response objects -
Angular - Typescript - Angular Components - Expressions - Data binding - Built-in directives.
(Chapter - 4)

UNIT V REACT
MERN STACK - Basic React applications - React Components - React State - Express REST
APIs- Modularization and Webpack - Routing with React Router - Server-side rendering.
(Chapter-5)

(iv)
TABLE OF CONTENTS
UNIT I

- 1
Chapter Basics of Full Stack (1 - 1) to (1 - 14)
1.1 Understanding the Basic Web Development Framework... 1-2
1.2 User 1-3
.. 1
1.3 Browser -3
1.4 Web Server 1-5
1.4.1 Apache.. .1 -5
1.4.2 IIS..... .1 -6
1.5 Backend Services. 1-6
....
1.6 MVC Architecture. 1 -7
1.6.1 MVC in Practical... .1-8
1.7 Understanding the Different Stacks. 1-8
1.7.1 Express 1-9
1.7.2 Angular. .1 -9
1.7.3 Node. 1- 10
1.7.4 MongoDB 1-10
- 11
1.7.5 React.... ....1
... 1 - 12
1.8 Two Marks Questions with Answers
UNIT II

Chapter -2 NODE JS (2 - 1) to (2 - 48)

2.1 Basics of Node JS 2-2


....
2.2 Installation.... 2- 2

2.3 Working with Node Packages... 2-5

2.4 Using Node Package Manager... 2-5


Installing Node Packages Modules.
... -7 2

2.4.1
2.4.2 Using package.json(Use of npm init). .2 -8
(v)
Node.js Built in Modules.
2.4.3 .2-9
2.5 Creating a Simple Node.js Application 2-11
2.6 Using Events 2- 13
2.6.1 Concept of Event Loop... .2-16
2.7 Listeners 2- 18
2.8 Timers ....2- 21
2.9 Callbacks. 2- 24
2.10 Handling Data I/0 2-25
....
2.10.1 Buffers. 2- 25
....2 - 26
2.10.2 Streams
2.10.3 File System
... 2 -
30

2.11 Implementing HTTP Services in Node.js... 2-34


2.11.1 URL Object.. ....2 -34
2.11.2 Query String and Form Parameters .2-35
. -
2.11.3 Request, Response and Server Object. 2 36

2.11.3.1 The http.ClientRequest Object.... ...2 - 37


2.11.3.2 The ServerResponse Object. ......2-39

2.11.3.3 The incomingMessage Object. ...2 - 43


.......... -
2.11.3.4 The http.Server Object.......... 2 45

2.12 Two Marks Questions with Answers 2- 45

UNIT III
-
Chapter -3 MONGODB (3 - 1) to (3 52)
3.1 Understanding NoSQL and MongoDB. 3-2
3.1.1 NoSQL. 3-2
MongoDB
..... -2
3.1.2 3
3.2 Building MongoDB Environment... 3-4
3.3 User Accounts. 3-13
3.3.1 Listing Users
...3-13
3.3.2 Create User Accounts... .3-14
3.3.3 Remove Users e.. 3-17
(vi)
3.4 Access Control
3- 17
3.4.1 Creating a User Administrator Account
.3-17
3.4.2 Creating Database Administrator Account .3- 19
3.5 Data Types in MongoDB
3-19
3.6 Administering Databases.
3- 20
3.7 Managing Collectíons. 3-22
3.8 Connecting to MongoDB from Node.js 3-29
3.9 Understanding the Objects Used in MongoDB Node.js Driver 3-30
3.10 Simple Applications 3-31
3.11 Advanced MongoDB. 3- 41
3.11.1 Indexing.
.3- 41

3.11.2 Aggregation. 3- 44

3.11.3 Map Reduce .3 - 46


-
3.12 Two Marks Questions with Answers ....3 48
UNIT IV

Chapter -4 Express and Angular (4- 1) to (4 - 66)


4.1 Implementing Express in Node.js. 4-2
4.1.1 Installing Express.. .... 4
-2
4.2 Configuring Routes. 4-4
4.3 Using Request and Response Objects 4 -6
4.4 Introduction to TypeScript 4-9
4.4.1 Installation. 4- 11
4.4.2 How to Write TypeScript Program ? .4 -13
4.5 Type Annotations 4- 16
4.6 Variables and Constants. 4 - 16
4.7 Understanding Interfaces. 4 - 18
4.8 Implementing Classes.. 4 - 22
4.9 Implementing Modules 4-24
4.10 Understanding Functions 4-27
4.11 Basics of Angular 4-29
(vii)
4.12 Angular CL.... 4 -30
Application in Angular. 4 -31
4.13 Creating First
4.13.1 Angular Lifecycle .4-33
ngModule
4.13.2 Understanding and Using 4
-34
4.14 Angular Architecture. 4-35
4.15 Angular Components. 4 - 37
4.16 Expressions. 4 - 42

4.16.1 Pipes
... 4 -
43

4.17 Data Binding. 4 - 44

4.18 Built-in Directives .. 4 -52

4.18.1 Structural Directives.. .4 -52


4.18.1.1 nglf Directive.... ...4 -52
4.18.1.2 ngfor Directive ......4. 55

4.18.1.3 ngSwitch Directive ...4-57


4.18.2 Attribute Directives. 4 -58

4.19 Two Marks Questions with Answers .4 -62


UNIT V

Chapter-5 React (5- 1) to (5 - 40)

5.1 MERN Stack.. 5-2


5.2 Basic React Applications.... 5-3
5.3 React Components 5-6
5-10
5.4
5.5
Inter Components Communication...
The props.
.. 5-12
5.6 React State..... 5-12
5.7 Express REST APIs. 5-15
5.8 Modularization and Webpack... 5-26
5.9 Routing with React Router
5-32
5.10 Server-side Rendering. 5-36
5.11 Two Marks Questions with Answers. 5-38

2)
Solved Model Question Paper (M- 1) to (M-

{vi)
UNIT I

1 Basics of Full Stack

Syllabus
Understanding the Basic Web Development Framework User Browser - Webserver - Backend
- -

Services - MVC Architecture Understanding the different stacks - The role of Express Angular
- -
- -
Node Mongo DB React

Contents
1.1 Understanding the Basic Web Development Framework
1.2 User
1.3 Browser
1.4 Web Server
1.5 Backend Services
1.6 MVC Architecture
1.7 Understanding the Different Stacks
1.8 Two Marks Questions with Answers

(1- 1)
Basics of Full Stack
Full Stack Web Development 1-2

Framework
Understanding the Basic Web Development
11|
What is Framework ?
applications which provides a foundation On
Framework is a platform for developing are the
software applications can be built. The front end frameworks soflwarc
which
-
packages that provide
The reusable code modules,
Standardized front end technologies and
and
made interface blocks for making the front end development faster
Ready
simple.
librarjes and
concept :
A web development framework is a collection of tools,
Basic
websites. It provides a basic structure and
technologies that are used to create web applications and
web applications quickly and eficiently.
set of conventions for developers to build
-
some important reason which indicate why do
we use web frameworks
Following are
framework is that it saves timne and enerov
1. Saves time : The most striking feature of web
in developing any app because the developer
doesn't need to worry about session
are taken care of by
handling. error handling and authentication logic. These functions
web frameworks.
app: The web framework itself takes
care of managing directories and
2. Well organized
files. This makes the complete application well organized.

3. Flexibility and customizable Add-ons, themes, plugins, widgets enable rapid


:

a lot of flexibility in code


customization on the web application. This brings out
development.
4. Code reusability : Framework also promotes the reuse of code.

uses good security


5. Security : Framework makes developers sure that the application
measurements because the framework itself takes care of it.

The components of web development framework are

1. User 2. Browser 3. Webserver 4. Backend servjces

TECHNICAL PUBLICATIONS- an
up-thrust for knowtedge
Full Stack Web Development 1-3 Basics of Full Stack

-
The components of web development framework are as shown below
Backend services

Database
Browser Webserver
MySQL
Request Server-side
Interacts Javascript (XML) Scripts
Oracle
HTML (CSs) CFiles
Response
User

Other
services

Fig. 1.1.1 Components of web development framework

Let us discuss them one by one

1.2 User
User is an important part of web development framework.
Users expectations from a website define the requirements for developing a good
website.
Normally an efficient and easy to use website is preferred by the user. They also expect
that the same website must behave closer to the applications installed on their
computers and mobile devices.
User interacts with the browser by using input devices such as mouse, keyboard on
PC or swipes and taps on mobile devices. The web framework processes the user input
and provides the required visual output.

1.3 Browser.
• Browser is an application for accessing websites. User interacts with the browser in the
web development framework.
The browser plays three roles in web framework -
1. It provides communication to and from the web server.
2. It interprets the data from the server and displays the visual output.
3. The browser handles user interaction through the keyboard, mouse, touchscreen or
other input device and takes the appropriate action.

TECHNICAL PUBLICATIONS- an up-thrust


for knowledge
Basics of FullStack
Full Stack Web Development 1-4

Browser to web server communication


:

browser makes use of HTTP and


For communicating with the webserver, the
HTTPS protocols.
is used for
HTTP stands for HyperText Transfer Protocol. This protocol
communication between browser and web server. It is a request/response protocol.
can be made by the user. Similarly the
HTTP also defines what type of requests that
HTTP protocol defines the format of those requests and responses.
an additional security
HTTPS protocol is similar to HTTP protocol but it adds
or not.
layer so that the user can decide whether to accept the connection
-
There are three types of requests to the server
server. This data
i) GET:The GET request is typically used to retrieve data from the
can be in the .html files or images.
-
server. For example
ii) POST: The POST request is used for sending the data to the
Credit card details while performing online shopping.
iii) AJAX
:
AJAX stands for Asynchronous JavaScript and Extensible Markup
Language. In AJAX, the GET or POST request is done directly by JavaScript
running in the browser.
Difference between GET and POST requests When a user submits his request using
:

user. But if
the GET method then the URL string displays the request submitted by the
the POST method is used then URL string does not show the submitted contents.
• Thecommon browsers are Internet Explorer, Mozilla Firefox, Google Chrome, Safari.

Rendering the bowser view :


The browser reads data from initial URL and then renders the HTML document to
build the Document Object Model (DOM).
The DOM is a tree structured object. The browser interprets each DOM element
and renders it to user's screen to build a webpage view.
Browsers get different types of data from multiple web server requests to build the
webpage.
Following are various types of files that are displayed by the browser -
HTML fles : The HTML files represent the static data.
CSS files : These files define how the elements on the page are to be
styled using fonts, colors, borders and so on.
Client side seript : Normally these scripts are in JavaScript files. These
scripts provide additional functionalities to the webpage, facilitate the

TECHNICAL PUBLICATIONS- an up-thrust


for knowledge
Full Stack Web Development
1-5 Basics of Full Stack
interactivity of user with the web page and provide any necessary logic
required todisplay the page and provide the functionality.
Media files : These are the files that contain images, videos and audio.
These files can be rendered as webpages.
Data : Any data such as XML, JSON or raw text can be provided to the
wcb server as a response to an AJAX request.
HTTP headers: The HTTP headers define the type of data in the request
as well as the type of data expected to be
returned back to the browser.
User interaction: User interacts with the browser with the help of input devices
such as
mouse clicks, keyboards, touchscreens.
The browser has an event system that captures
the user events and then takes appropriate action. This action can be loading the
web
page obtained from the server as a response or
displaying the pop-up menu.

1.4 Web Server


Web server is a special type of server to which the web browser submits the request
of a web
page which is desired by the client. There are some
popularly used web servers such as Apache and
IIS from Microsoft.

Functions of web server


Various functions of web server are -
1. The web servers accept the requests from the web browsers.
2. The user request is processed by the web server.
3. The web servers respond to the users by providing the services which they demand
for
over the web brOWsers.
4. The web servers serve the web based applications.
5. The DNS translates the domain names into the IP addresses.
6. The servers verify given address exists, find necessary files, run
appropriate scripts,
exchange cookies if necessary and return back to the browser.
7
Some servers actively participate in session handling techniques.

1.4.1 Apache
• It is an excellent server because of its two important features: Reliability and
Efficiency.
Secondly it is more' popular because it is an open source software.
That means it is
freely available to anybody. Apache web server is best suitable
for UNIX systems but it

TECHNICAL PUBLICATIONs- an up-thrust for knowledge


1-6 Basics
Full Stack Web Development ofFullStark
web server can be configurcd
can also be used on Windows box. The apache asper
file httpd.conf. This file is present in the Apache thc
requirements using the sollware
package.

1.4.2 |IS
internet information server
a
The internet information services or is kind of
wcb sCrver
provided by Microsoft. This server is most popular on the Windows platforn.
-
Following are some differences between Apache and lIS servers
Sr. No. Apache web server IIS web server
1
Apache web server is useful on both unix IIS web server is used on windows
based systems and on windows platform. platform.

2. It is an open source product. It is a vendor specific product and can


be
used on windows products only.

3 The Apache web server can be controlled For the IIS server, the behaviour is
by editing the configuration file htpd.conf controlled by modifying the window
based management programs called IIS
snap in. We can access
IS snap-in
through the Control-Panel
>Administrative Tools.

1.5 Backend Services


Backend services are the services
that run behind the web server.
data to the web server which is These services provide the
requested by the web browser.
The most commonly used backend
service is a database that stores
the information.
When a browser requests some
data to the web server. the
(backend service) or some other web server connects to the dalavas
backend service retrieves
the information, formats
sends it back to the browser. it and
Similarly, when the data conmes
browser to
server connects to the web server
inthe form of request, then the
web
the database and updates the data.

Review Question
1. Explain web development
framework with suitable
components of it. block diagram. Also explain the

TECHNICAL
PUBLICATIONS.
an up-thrust
for knowledge
Full Stack Web Development 1
-7 Basics of Full Stack

1.6 MVC Architecture


The MVC stands for Model. View and Controller. It is a pattern for the architectural
framework.
It consists of three parts -
:
1. Model This part of the architecture is responsible for managing the application data.
This module responds to the request made from view. The model gives instructions to the
controller to update when the response is made.
2. View This part takes care of the presentation of data. The data is presented in desired
:

format with the help of view. This is a script based system using JSP, ASP, PHP and so
on.

3. :
Controller The controller receives input, validates it and then performs business
operations that modify the state of the data model. The controller basically responds to
user requests and performs interaction with the model. Refer Fig. 1.6.I.

II
alerts Controller
updates
about event
model
(IV)
Notifies change
User interacts
View Model
takes model data
and updates view

Fig. 1.6.1 MVC architecture

Model represents the data.


View is the user Interface.
Controller is the request handler.
Features of MVC framework
1. Separation of logie There is a separation of application tasks such as input logic,
:

business logic and UI logic. This makes testing and debugging easy. Modification in one
component does not affect the other.
2. Ability to provide multiple views : In MVC model, we can create multiple views.
3. Faster development process :
MvC supports rapid and parallel development. If an
MVC model is used to develop any particular web application then it is possible that one
programmer can work on the view while the other can work on the controller to create
the business logic of the web application.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Basics of Full Stack
Full Stack Web Development 1-8
any
Returns data without formatting
:
MVC pattern returns data without applying
4.
can be uscd and called for use with anv
formatting. Hence, the same components
interface.
are
5. Customization : It is anextensible and pluggable framework. MVC framework
or customized.
designed so that the components can be casily replaced

1.6.1 MVC in Practical


order to understand the analogy ofMVC let us take
a real life cxample.
In

Let's take the example of a restaurant.


menu and then
When you visit a restaurant, the waiter presents you with menu. You view the
a

tell the waiter your order. The waiter notes down the order and passes it to the chef, in the kitchen.
The chef uses the raw materials from the refrigerator and cooks the dish. The waiter then takes the
dish from the kitchen and then presents it to you, after which you can enjoy your meal.

Here the menu and the food come under the view component.
The waiter acts as a controller.
The chef and the refrigerator can be thought of as the model.

ReviewQuestions
1. Explain MVC architecture with a suitable diagram.
2. Enlist the features of MVCframework.

17 Understanding the Different Stacks


The stack development refers to the end to end application software development. The Node,js
to angular stack consists of- MongoDB, express, angula, Node.js.
The basic block diagram of how the Node.js to angular fits into the web framework model is as
-
shown below

TECHNICAL PUBLICATIONS an up-thrust for knowledge


Full Stack Web Development 1-9 Basics of Full Stack
Backend services

Database
Webserver
Browser
Angular Node.js
Request MongoDB
Express
Interacts
Javascript JSON
XML webserver

HTML CSS Server-side


scripts
Response
User Files

Other
services

Fig. 1.7.1 Full stack web development framework

1.7.1 Express
Express is used for server side development in full stack. As it is running in Node.js, it is easy
to configure, implement and control the web application.

Following are the reasons why express is a great framework to start from -
1) Routing : Express JS provides a routing mechanism so that it is possible to reach to
different web pages using the URLs.
2) Error handling: Express provides built-in error handling for documents.
3) Easy integration : Express server can easily be implemented behind an existing reverse
proxy system. This allows it to be easily integrated into your existing secured system.

4) Cookies : Express provides easy cookie management.


:
5) Session and cache management Express has session management and cache
management facility.

1.7.2 Angular
Angular is a client side framework developed by Google. It is written in TypeScript. angular
provides all the functionalities needed to handle user input in the browser, manipulate data on the
client side. It also controls how elements are displayed in the browser window.

TECHNICAL PUBLICATIONS- an up-thrust for knowedge


Full Stack Web Development 1- 10 Basics of FullStack

Following are the reasons why angular is agreat framework to start from -
1) Clean : Using angular the developer can develop clean and logical code.
2) Extensibility :
The angular allows to extend almost every aspect of the language to

provide the custom implementation.


3) Reusable Code : Using angular the reusable code can be written.
4) Data binding : Using angular the data can be bound to HTML elements using the scone
mechanism.
5) Support : As the angular framework is developed by Google, there exists a great suppon
for developing the web applications.
6) Compatibility: Angular is based on TypeScript. Hence it is easy to integrate angular
into the working environment.

1.7.3 Node
The Node.js is a development framework that uses Google's
V8 JavaScript engine. The
meaning of V8 JavaScript engine is that it parses and executes the
JavaScript code. The Node.js
code is written in JavaScript and then compiled.
Following are the reasons why Node.js is a great framework to start
from -
1) Easy to use : Node.js is very much easy to set up.
Developing the web applications using
Node.js is also very easy.
2) Extensibility : New modules that are required to extend the Node.js functionality can
be
developed at any time.
3) Event driven scalability : In Node.js, the web requests are processed on the same thread
using a basic event model. Node.js uses a single thread model with event looping.
Similarly the non blocking response of Node.js makes it highly scalable to serve large
number of requests.
:
4) Efficient The Node.js is built on V8 JavaScript engine and it is very fast in code
execution.
5) Use of JavaScript, end-to-end: The one of the important reasons of using Node.js is
that it allows to write both server and client side scripts JavaScript. This makes easier
i
to work for client side developers as well as for server side developers.

1.7.4 MongoDB
MongoDB is a part of backend services, It is basically a scalable NoSQL database. The data is
stored in the form of a JSON object.

TECHNICAL PUBLICATIONS,- an up-thrust for knowedge


Full Stack Web Development 1- 11 Basics of Full Stack

Following are the reasons why MongoDB is a great framework to start from -
1) Document orientation : The data is stored in the document form in the MongoDB.
: It is
2) High performance the highest performing database.
3) High scalability: The MongoDB allows horizontal scalability by sharing data across
multiple servers.
4) High availability : MongoDB provides high availability and redundancy with the help of
replication. That mcans it creates multiple copies of the data and sends these copies to a
different server so that if one server fails, then the data is retrieved from another server.

1.7.5 React
ReactJS is an open source, component-based front end JavaScript library maintained by
facebook. This library is responsible only for the view layer of the application. That means this
JavaScript is for building user interfaces.
Following are the reasons why MongoDB is a great framework to start from -
1) Virtual DOM: DOM stands for Document Object Model. It also provides a way to
update the content, structure and style of the document. Virtual DOM is a representation
of the original DOM. When a user updates something on the web application, DOM gets
updated. Updating the DOM is very slow, most of the JavaScript frameworks update the
whole DOM which makes it slower. But actually there is no need to update the whole
DOM, instead, these frameworks should update only the part of DOM that is required to
update. This is what the virtual DOM does. This is why ReactUS's DOM manipulation is
much faster than other frameworks. Due to this property, whenever any change is made
in the web application, then those changes are reflectedon the web page within no time.

2) Components : This feature allows the web developer to create custom elements which
can be reused in HTML.

3) JSX: JSX is an extension of JavaScript syntax. JSX can be seen as a combination of


javascript and XML. The syntax of JSX is very simple that makes writing components
very easy.
4) One way data binding : The ReactJS is designed in such a way that it follows,
unidirectional or one way data binding. That means, data is allowed to flow in one
direction at a time. This helps in achieving greater control over the application. This
makes helps in increasing the efficiency of an application.

TECHNICAL PUBLICATIONS. an up-thrust for knowedge


Full Stack Web Development 1-12 Basics of Full Stack

Review Questions
1. Explain the use of
Nodejs in full stack development.
2. Write short note on - MongoDB.
3. Give the reasons - Why is express useful in web frameworks ?
4. Explain the role of react in web framework.

1.8 Two Marks Questions with Answers


Q.1 What is web development framework ?
:
Ans.
• A web development framework is a collection of tools, libraries and technologies
that are
used to create web applications and websites.
• It provides a basic structure and set of conventions for developers to build web applications
quickly and efficiently.
Q.2 Whydo we use web framework ? Give any two reasons.
Ans. :

1. Saves time :
The most striking feature of web framework is that it saves time and energy in
developing any app because the developer doesn't need to worry about
session handling,
error handling and authentication logic.
These functions are taken care of by web
frameworks.
2. Flexibility and customizable :
Add-ons, themes, plugins, widgets enable rapid
customization on the web application. This brings out a lot of flexibility in code
development
Q.3 What are the components of web development framework
?
Ans. The components of web development framework are -
:

(1) User (2) Browser (3) Web Server (4) Backend services
Q.4 Give the importance of browser
: -
Ans. The browser plays three roles in web framework
1. It provides communication to and from the web server.
2. It interprets the data from the server and displays the visual output.
3. The browser handles user interaction through the keyboard, mouse,
touchscreen or other
input device and takes the appropriate action.

TECHNICAL PUBLICATIONs- an up-thrust


for knowledge
Full Stack Web Development 1- 13 Basics of Full Stack

Q.5 What is GET and POST request ?

Ans.:
i) GET:The GET request is typically used to retrieve data from the server. This data can be in

the .html files or images.


-
ii)) POST: The POST request is used for sending the data to the server. For example Credit

card details while performing online shopping.


Q.6 What is web server ?
Ans. : Web server is a special type of server to which the web browser submits the request of a
web page which is desired by the client.
Q.7 Enlist the functions of web server
-
Ans. :
Various functions of web server are
1.The web servers accept the requests from the web browsers.
2. The user request is processed by the web
server.
over
3. The web servers respond to the users by providing the services which they demand for
the web browsers.
4. The web servers serve the web based applications.

Q.8 What do you mean by backend services

Ans. :

1) Backend services are the services that run behind the web server. These services provide the
data to thé web server which is requested by the web browser.
2) The most commonly used backend service is a database that stores the information.
Q.9 What is MVC?
:
Ans.
1. Model : This part of the architecture is responsible for managing the application data. This
module responds to the request made from view. The model gives instructions to the

controller to update when the response is made.


This part takes care of the presentation of data. The data is presented in desired
:
2. View
format with the help of view. This is a script based system using JSP, ASP, PHP and so on.
3. Controller : The controller receives input, validates it and then perforns business operations
that modify the state of the data model. The controller basically responds to user requests
and performs interaction wvith the mnodel.

TECHNICAL PUBLICATIONs - an up-thrust for knowledge


1- 14
Basics of Full Stack
Full Stack Web Development

Q.10 stack ?
VWhat is full
anv weh
:
Full stack development is development of both front cnd and back cnd of
Ans.
application.
2. Express 3. AngularJS 4. Nodc.js 5. Rcact.js
The full stack consists of
-1. MongoDB

TECHNICAL PUBLICATIONs-an up-thrust for knowledge


UNIT II

2 NODE JS

Syllabus
Basics of Node JS - Installation Working with Node packages Using Node package manager -
- -

Creating a sinple Node.js application Using Events Listeners - Timers - Callbacks - Handling
-
-

Data I/0 - Implementing HTTP services in Node,js.

Contents
2.1 Basics of Node JS
2.2 Installation
2.3 Working with Node Packages

2.4 Using Node Package Manager


2.5 Creating a Simple Node,js Application
2.6 Using Events
2.7 Listeners
2.8 Timers
2.9 Callbacks
2.10 Handling Data l/0
2.11 Implementing HTTP Services in Node.js
2.12 TWo Marks Questions with Answers

(2- 1)
Full Stack Web Development 2-2 NODE JS

2.1 Basics of Node JS


• Node JS is an open source technology for server.
Using Node.js we can run JavaScript on server.
• Itruns on various platform such as Windows, Linux, Unix, and MacOS.

Uses of Node.js
It can perform various tasks such as -

1) tcan create, open, read, delete, write and close files on the server.
2) It carn collect form data.
3) It can also add, delete, modify data in databases.
4) It generate dynamic web pages.

Features
Following are some remarkable features of node.js -

1) Non blocking thread execution :


Non blocking means while we are waiting for a
response for something during our execution of tasks, we can continue
executing the
next tasks in the stack.
2) Efficient : The node.js is built on V8 JavaScript engine and it is very fast in code
execution.
3) Open source packages : The Node community is enormous and the number of
permissive open source projects available to help in developing your application in
much faster manner.

4) No buffering : The Node.js applications never buffer the data.


5) Single threaded and highly scalable : Node.js uses a single thread model with event
looping. Similarly the non blocking response of Node.js makes it highly scalable to
sever large number of requests.

Review Question
1. What is Node js ? Enlist thefeatures ofNodejs.

2.2 Installation
• For executing the Nodejs scripts we need to install it. We can get it downloaded from
htps:/nodejs.org en.

TECHNICAL PUBLICATIONS. an up-thrust for


knowedge
Full Stack Web Development 2-3 NODE JS

The installation can be done on Linux or Windows OS. It has very simple installation
procedure.

nde
HOME ABOUT DOWLOADS DOCs GET
INOKD SriSTTY

Node.js is a JavaSeript runtime built on Chrome's V8 JvaScript engine.

MBlacktivesMatter

New security releases now available for 15.x, 14.x, 12.x and 10.x
release lines

Download

14.16.0 LTS 15.11.0 Current


Recommended For Most Users tatest Features
Serof to tog
Chano AP Oncs
CAhet Deetikds Changeic A Sees DEhr Cnkcuts

orhavealaok at the long Ietn Suocat ISlschedule

Download node MSI for windows by clicking on 14.16.0 LTS or 15.l1.0 Current
button.
• After you download the MSI, double-click on it to start the installation as shown below.

Nodejs Setup

Welcome to the Node.js Setup Wizard

nade The Setp Wzard wd rstal Node.s on you computer.

Back Niext Cancel

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 2-4 NODE
JS
• Click Next button to read and accept the License Agreenment and then click Install :
will install Node.js quickly on your computer. Finally, click finish to conplete the
installation.
Verify Installation
• In order to verify the installation we have to open a command prompt and type the
following command -

Command Prompt X

D:\>node -v
14.15.4
D:\>

If the node.js is successfully installed. then some version number of the node.js which
you have installed in your PC will be displayed.
After successful installation we can now execute the Node.js document. The Node.js file
has extension js.
Following is a simple node.js program which can be written in notepad.
app.js
console.log("Weicometo first Node.js Application program");

Output

C Command Prompt

þ:\>node app.js
elcome to first Node.js Application program

p:\

TECHNICAL PUBLICATIONS- an up-thrust for


knowtedge
Full Stack Web Development 2-5 NODE JS

2.3 Working with Node Packages


A node packaged module is a packaged library that can be easily shared, reused and
installed in different projects.
The node packages include a package.json file that defines the packages.
The package.json is an important file of any node project. It records the important
metadata about a project. The package.json file consists of -
name : The name of the application/project.
:
version The version of application. The version should follow semantic versioning
rules.
deseription The description about the application, purpose of the application,
:

technology used like React, MongoDB, etc.


main : This is the entry/starting point of the app. It specifies the main file of the
application that triggers when the application starts. Application can be started using
npm start.
seripts : The scripts which need to be included in the application to run properly.
engines : The versions of the node and npm used. These versions are specified in case
the application is deployed on cloud like heroku or google-cloud.
keywords : It specifies the array of strings that characterizes the application.
author : It consists of the information about the author like name, email and other
author related information.
license : The license to which the application confirms is mentioned in this key-value
pair.

2.4 Using Node Package Manager


A package in Node.js contains all the files you need for module.
a

Modules are JavaScript libraries you can include in your project.


The NPM stands for node package manager.
NPM consists of two main parts :
1) A CLI (command-line interface) tool for publishing and downloading packages,

2) An online repository that hosts JavaSeript packages.


NPM gets installed along with the installation of node.js. To verity the presence of npm
package on your machine install following command

TECHNICAL PUBLICATIONS. an up-thrust for knowledge


Full Stack Web Developmernt 2-6 NODE JS

C CAWindows\ System32\cmd.exe

D:\NodeJSExamples>npm version
5.14.10
b:\NodeJSExamples>

There are various command line options that npm uses. These options are as follows -
Option Purpose Example
install Installs the
packages either using a npm install express.
package.json or from the repository or from
a local location.
npm install.

Search Searches the module packages in the npm search express.


repository.
install -g Installs the package globally. npm install express -g.
remove Removes the specific module. npm remove express.
View Displays the module details. npm view express.
Publish Publishes the module defined by a npm publish.
package.json file to registry.
unpublish Unpublished the module which is published npm unpublish testModule.
already.

Owner Manages the ownership of published npm owner add <user> <package-spec
packages.
npm owner rm <user> <package-spec>
Is :
List all the users who have access to
npm owner ls <package-spec>
modify a package and push new versions.
Handy when you need to know who to bug
for heip.

add : Add a new user as a maintainer of a


package. This user is enabled to modify
meladata, publish new versions and add
other oWners.
rm :
Remove a user from the package
owner list. This immediately revokes their
privileges.

TECHNICAL PUBLICA TIONS- an up-thrust for knowledge


Full Stack Web Development 2-7 NODE JS

2.41 Installing Node Packages Modules


For installing any node.js module we have to use the installcommand. For example -

C\Windows\ System3cmd exe X

D:
\odeJSExamples>npm express +
install as Issue this command
a
D nôtlée created
HARN
lockfile
No
package -lock.json. You should comit this file.
Lti mypackageg1.0.1 repository field.
[email protected]
added 50 packages from 37 contributors and sudited 50 packages in 4.969s
found 0
vulnerabilities

D:\ModeJSExamples>,

As soon as we issue this command the package-lock file gets generated in the current
folder.
For using this module in our program we have to use following command -
var ex = require('express');
Example of using the existing module
Step 1: We will install the module upper-case by issuing the install command

G CAWindows\System32\cmd.exe X

D: \NodeSExamples>npa
install upper-case
npn WARN nypackageg1.0.1 No repository field.

[email protected]
ladded 2 packages from 2 contributors and audited 52 packages in 4.047s
found e vulnerabilities

D:\NodeJSExamples>

TECHNICAL PUBLICATIONs- an up-thrust for knowledge


Full Stack Web Development 2-8 NODE
JS
Step 2: You can locate this module inside your_ folder/node_modules. Now open an,

suitable text editor and write node js script that makes use of this module.

moduleDemo.js
var upp ch require(upper-case);
console.log(upp ch.upperCase(iam proud of you"):

Output

CAWindows\ System32\cmd.exe X

D:\NodeJSExamples>node noduleDemo.js
I AM PROUD OF YOU

D:\NodeJSExamples>

2.4.2 Using package.json(Use of npm init)


We can create our own package using following steps

Step 1: Create a sample folder. Open command prompt and go to that directory location. For
instance -I have created a folder named nodejsexamples. Issue the command npm init at the
command promp.

Microsoft Windoss [Version 10.e.19841.8041)


Kc) 2820 Microsoft Corporation. All rights reserved.

D:WlodeJSExenples>npn init
This utility will walk you through creating a package.json file.
7t only covers the most conon items, and tries to guess sensible defaults.
See np help init for definitive documentat ion on these fields
end exactly that they do.
Usenpn install <pk» efterwards to install a package and
sve it as a dependency in the package.json file.

Press L st any tise to quit.


package name: (nodejsexemples)

TECHNICAL PUBLICATIONS an up-thrust for knowledge


Full Stack Web Development
2-9 NODE JS
Step 2: Now fill the informnation about the package.

CC1WindowSystem 2\cmd eve

Press C at any time to quit.


package name: (node jsexamp les) mypackage
version: (1.0.0) 1.0.1
description: This is my first package!!!
entry point: (callbackDemo. js)
test command: runpackage
git repository:
keywords:
author: A.A.Puntambekar
license: (ISC)
About to write to D:\NodeJSExamp les\package.json:

"name": "mypackage",
"version": "1.0.1",
"description" : "This is my
first package!!!",
"main": "callbackDemo.js",
"scripts": {
:
"test" "runpackage"
"author": "A.A. Puntambekar",
"license": "ISC"

Is this OK? (yes) yes

p:\NodeJSExamples>

Once you execute the above commands, the package.json gets created. You can open
and test it using a simple notepad.

2.4.3 Node.js Built in Modules


• Module is nothing but the set of functions that can be used in our
application. Node.js
has various built in modules that can be used in our application without any installation.
• To include the module, we use require) function with
the name of the module. Let us
discuss some important built-in modules.
(1) assert
This module is used during the testing of expressions. If an expression evaluates to 0 or
false, an error thrown and the program gets terminated.

Step 1: Open Notepad and create a js file as follows. I have created an application using the
name app.js. Here is the code.

app.js
var assert = require('assert');
assert(10< 2);

TECHNICAL PUBLICATIONS an up-thrust


for knowledge
Full Stack Web Development 2-10 NODE
Is
prompt and issue the command
Step 2: Now, open the command
node app.js
Please refer followring screenshot

CIWndows\Systen32\nd eve

E:NOdeJSExamples \modules>node app.js


assert.js:383
throw err;

a
AssertionError (ERR ASSERTION]: The expression evaluated to falsy valve:
assert(1e 2)

Note that as the 10 is not less than 2, the above code will raise the error namcd
AssertionError.
(2) cluster
The cluster module helps in creating a child process. Both the main and child processes
can run simultaneously and share the same server port. Let us see its use with the help of
a
demo example.
Step Open Notepad and create a js file as follows.
1 : I have created an application using the
name app.js. Here is the code.
app.js
var cluster = require(chuster');
Y (cluster.isWorker) {
Console.log(Child Process);
}else {
console.log('Main Process');
cluster.fork():
cluster.fork();
chuster.fork():

Step 2: Now, open the command prompt and issue the command.
node appjs
Please refer following screenshot

CaWindows System32Z\cTd eTE - node apps X

EHode)SExamples\modules>node app.js
Main Process
Child Process
Child Process
Child Process

TECHNICAL PUBLICATIONS- an up-thrust


for knowledge
Full Stack Web Development NODE JS
2-11
(3) os

The os module provides information about the operating system of your computer.
Step 1: Open Notepad and create a js file as follows. I
have created an application using the
name app.js. Here is the code.

app.js
var os = require('os');
console.log("Platform on My Computer:" + os.platform():
console.log("Architecture of My Computer:" + os.arch()):

Step 2 : Now, open the command prompt and issue the command
node app.js
Plcase refer following screenshot

CAWindows\System32\Cmdexe

E:\NodeJSExamples\modules>node app.js
Platform onMy Computer: win32

Architecture of My Computer: x64


E: \NodeJSExamples\modules>

2.5 Creating a Simple Node.js Application


The console object is a global object which is used to print different levels of messages to
stdout and stderr.
The most commonly used methods console object are console.log console.info,
console. warn and console.error. Let us discuss them with illustrative examples,
1) console.log(|data|, ...) :
t is used for printing to stdout with newline. This function
can take multiple arguments similar to a printf statement in C.

console1.js
var emp name 'Ankita,
emp depts = {
dept1: 'Sales', dept2: 'Accounts'

console.log(Name: %s'+\n't Departments: %i emp name, emp depts)}

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 2-12 NODE
JS

Output

oL Command Prompt

D: \ModeJSExamples>node
consolel.js
Name: Ankita
Departments: "depti":"Sales,"dept2":"Accounts"}
D: \Node3SExarples

2) console.info(|data]|, ..]) :This method is similar to console.log.


console2.js
var emnp name = Ankita,
emp depts={
dept1: 'Sales',
dept2: 'Accounts'}:
console.info(Name: %s+\n'+ Departments: 6j,emp name, emp
depts);

Output
Name: Ankita
Departments: ('dept1"Sales, dept2 Accounts")
3) console.error (|dáta]|, ..) : This method prints to stderr
with newline
console3.js
var code = 401
Console.error(Error!! code)

Output
Error!!! 401

4) console.warn(ldata]|, ..]): This method is similar to console.error() method.


Consider following example - In which using the fs module we open a text file.
If the file
does not open successfully then console.warn() method displays the warning message.

console4.js
var fs = require(fs'):
fs.open("input.dat",T,function(er,fs){
if(err)
console.warn(e);
else
console.log("File opening successful!!!");

TECHNICAL PUBLICATIONS- an up-thrust


for knowledge
Full Stack Web Development NODE JS
2-13

Output

CCommand Prompt

D: \WodeJSExamples>node console4, js
[Error: ENOENT: no such file or direcory, open 'D: MlodeiSExamples\input.at'] {
errno: -4058,
code: ENOENT
syscall: 'open
path: "D:\\Mode1SExamples\\inpüt dat

D:\NodeJSExamples>

Review Question
Explain amy
four methods of console object in nodejs with suitable examples.
2.6 Using Events
• Event-driven programming is a programming paradigm in which the flow of the
program is determined by events such as user actions (mouse clicks, key presses). sensor
outputs, or messages from other programs/threads.
Event
loop

Event emitter Event queue Event handlers

Fig. 2.6.1 Event driven architecture in node.js

What is an Event ?
Every time when a user interacts with the webpage, an event occurs when the user clicks
the mouse button or presses some key on the keyboard.
When events are triggered, some functions associated with these events get executed.
Event driven programming makes use of the following concepts -
i) When some events occur, an event handler function is called. This is basically a call
back function.
ii) The nain program listens to every event getting triggered and calls the associated
event handler for that event.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 2-14 NODI

Concept of Event Emitter:


The Even emiter is a module that facilitates communication betwecn objccts.
-
The emitter objects performs following tasks
1) It emits named events.
2) Registed and unregisted listener functions.
Basically EventEmitter is a class which can be uscd to raise and handle custom cvenls
Following are some commonly used methods of EventEmitter class.
Method Purpose
on(event, listener) This function adds the listener function to the cnd of the
listeners aray for the specified event.

once(event, listener) Adds a one-time listener for the event. This listener is invoked
only the next time the event is fired, after which it is removed.

emit(event, [argl]. [arg2]. [...]) Raise the specified events with the supplied arguments.

Steps for using event handling in Node.js


Step 1: import the events' module and create an instance of it using following code -
var events = reguire('events);
Step 2 :Then create an instance of EventEmitter(0 class. This instance is
created because we
have to call on) and emit() functions using this instance.

Step 3: Then define a callback function which should be called on occurrence


of an event.
This function is also called as event listener function.
Step 4: Then register the event using the on(0 function. To this function name of the event and
callback function is passed as arguments.

Step 5 : Finally raise the event using the emit) function.


Example Code

eventDemo1.js
/ get the reference of EventEmítter class of events module
var events = require(events');

T/create an object of EventEmitter class by using above reference


var em = new events.EventEmitter():

var myfunction = function() {


console.log("When event occurs, My Function is called")

TECHNICAL PUBLICATIONS- an up-thrust


for knowledge
Full Stack Web Development 2- 15 NODE JS

//Bind FirstEvent with myfunction


em.on(FirstEvent', myfunction):

1/ Raising FirstEvent
em.emit(FirstEvent');

Output
DANodeJSExamples>node eventDeno1.js
When event occurs, My Function is called.
Program Explanation :
In above program,
1) We have to import the 'events' module.
2) Then we create an object of the EventEmitter class.
3) For specifying the event handler function, we need to use the on) function.
4) The on) function requires two parameters - Name of the event to be handled and the
callback function which is called when an event is raised.
5) The emit() function raises the specified event.

Example code for passing data along with event


We can pass some data inside the event, following example illustrate the same -

eventDemo1.js
the reference of EventEmitter class of events module
Lget
var events = require(events);
lcreate an object of EventEmitter class by using above reference
var em = new events.EventEmitter();
var myfunction = function(data1,data2) {
console.log("When event occrs, My Function is called');
console.log("Data passed is: "+data1+" "+data2):

//Bind FirstEvent with myfunction


em.on(FirstEvent', myfunction):
/ Raising FirstEvent
em.emit(FirstEvent'data1 'data2'):

Output
DINodeJSExamples>node eventDemo 1.js
When event occurs, My Function i called
Data passed is: data1 data2

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
Full Stack Web Development 2- 16 NODE

2.6.1 Concept of Event Loop


• Node Js is a single threaded system. So it executes the next task only after complelon.
previous task.
The event loop allows Node.js to perform non-blocking VO opcrations cvenif t
JavaScript is single threaded.
Event loop is an endless loop which waits for tasks, cxecutes these tasks and sleeps unt

it recejves next task.


The event loop allows us to use callback functions.
The event loop executes task from event queue only when the callstack is cmpty. Enp
callstack means there is no ongoing task.
Event loop makes execution fast.

Event Loop Execution Model


JavaScript Engine Thread
Pool

Blocking
myapp.js Calistack Event Queue
operations
Event loop)
Task1 Taskn Execute callback

Fig. 2.6.2 Event loop execution

The Event Loop is a main loop running continuously for executing the callback
functions. When an async function executes, the callback function is pushed into the
queue. The JavaScript engine doesn't start processing the event loop until the code after
an async function has executed.

Example Code
console.log(Task1");
console.log(Task2'):
setTimeout(function() {console.log(Task3") }.1000);
console.log("Taks4");

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development
2- 17 NODE JS

Output

Ga Command Prompt X

D:\Node)SExamples>node EventLoopDemo.js
Task1
Task2
Taks4
Task3

D:\NodeJSExamples>

Phases of Event Loop


Various phases of event loop are
-

Pending
Callbacks

Idle,
Timers Prepare

Close Poll
Callback

Check

Fig. 2.6.3

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 2-18 NODE
J
1) :
This is the first phase in the event loop. It finds expired timers in e
Timers
iteration (also known as Tick) and exccutes the timers callbacks CTcated
by seiTimout and setinterval.
2) Pending callbacks : It handles VO callbacks deferred to the next iteration, Such
handling TCP socket connection error.
3) Idle. prepare : It is used internally.
4) Poll :
The Poll phase calculates the blocking time in every iteration to handle |0
callbacks.
5) Check : This phase handles the callbacks scheduled by setlmmediate(), and the

callbacks will be cxecuted once the Poll phase becomes idle.


6) Close callback : This phase handles callbacks if a socket or handle is closed suddenl,
and the close' event willbe emitted.

2.7 Listeners
An event listener is a technique or a function that waits for an event to occur. The
listener is programmed to react to an input or signal by calling the event's handler.
The event module allows us to create and handle custom events in Node.js.
The EventEmitter class is used to raise and handle the events.
Following are some commonly used properties and methods that implements the event
listeners.
Method Purpose
addListener(event, listener) Adds a listener to the end of the listeners array for the
specified event. No checks are made to see if the listerier has
already been added.

on(event, listener) It can also be called as an alias of emitter.addListener0

removelListener(event, listener) Removes a listener from the listener array for the specified
event. Caution :Changes array indices in the listener array
behind the listener.

removeAlIListeners((event]) Removes all listeners, or those ofthespecified event.

listeners(event) It returns an array of listeners for specified event.

listenerCount(event) It returns the number of listeners listening to the specified


events.

prependOnceListener(event, Iistener) It will add the one-time listener to the beginning of the
array.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 2- 19 NODE JS

sctMaxlListeners(int) This method sets the number of listeners to the particular


event. By default a maximum of 10listeners can be
registered for any single event.

getMaxistencrs() It will return the max listeners value set by


setMaxListeners() or default value 10.

Example Code
var events = require('events');
var eventEmitter = new events.EventEmitter();

I/Event listener #1
var listener1 = function listener 1() {
console.log('Event listener#1 executed.'):

I/ Event listener #2
var listener2 = function listener2() {
console.log('Event listener#2 executed.');

I/Event listener #3
var listener3 = function listener3() {
console.log('Event istener#3 executed.):

I/Bind the 'myevent' event with the listener1 function


eventEmitter.addListener('myevent, listener 1);

Bind the 'myevent' event with the listener2 function


/

eventEmitter.on('myevent', listener2);
eventEmitter.on('myevent, listener3);

//Raise the events


eventEmitter.emit('myevent'):

/Display total number of events


console.log("Number of Eventlisteners are: "teventEmitter.listenerCount('myevent'):

"/Display the curent status of event queue


console.log("Following are the events in the queue...\n");
console.log(eventEmitter.listeners('myevent');

/Remove the bin ding of listener1 function


ventEmitter.removeListener('myevent', listener 1);

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 2-20 NODE

Console.log("'Event Listener#1 is removed");

T/Display the curent status of event queue


console.log('Following are the events in the queue.n'):
COnsole.log(eventEmitter.listeners('myevent');
console.log('Number of Eventlisteners are:+eventEmitter.listenerCount(myevent"));

1/Removing all the events


Consolelog(Removing all the events."}:
eventEmitter.removeAllListeners(myevent);

I/Display the current status of event queue


console.log('Following are the events in the queue...\n");
console.log(eventEmitter.listeners('myevent):
console.log(Number of Eventlisteners are:"+eventEmitter.listenerCount(myevent');

Output
Event listener#1 executed.
Event listener#2 executed.
Event listener#3 executed.
Number of Eventlisteners are: 3
Following are the events in the queue...

IFunction: listener1], (Function: listener2]. [Function: listener3] |

Event Listener#1 is removed


Following are the events in the queue...

IFunction: listener2]. (Function: listener3) ]

Number of Eventlisteners are: 2


Removing all the events.
Following are the events in the queue...

Number of Eventlisteners are: 0


Progran Explanation : In above program,
1. Three functions are created as event listeners. Then
using eventEmitter.addListener)
and eventEmitter.on() methods are used to
bind the events with the correspondng
functions.
2. Then using eventEmitter.event(0
method, the events are raised.
3. We have used the eventEmitter.listenerCount() method to get the
total number o
events that are active.
4. The eventEmitter.listeners) method
is used to display the array of registered evens.

TECHNICAL PUBLICATIONS
an up-thrust for knowledge
Full Stack Web Development 2
-21 NODE JS

5. We have also uscd removeListener() method to remove one listener and


removeAlllisteners) method to remove all the listeners.

2.8 Timers
Timers module in Node js provides a way for scheduling the functions to be executed
on some given timc.

For using the timers module in Node.js it is not required to import it via require)
function as all the methods are globally available to JavaScript API. Hence we do not
have to use “require" in the source code while using timer functions.
There are three set timer functions used in Node.js
1.setTimeout() 2. setImmediate() 3. setlnterval()

-
Let us understand them with suitable examples
1) setTimeout() :
This function is used to set one time callback after delaying by some
milliseconds.
Syntax
setTimeout(function,delay in milliseconds)
Timer1.js
console.log("Task1");
setTimeout(function() {console.log("Taks2:Executing After 4 seconds") }4000);
console.log("Task3");

Output

CN Command Prompt X

D:\NodeJSExamples>node Timer1.js
Task1
Task3
Taks2:Executing After 4 seconds

D:\Node]SExamples>

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


NODE
Development
2-22
Ful Stack Web
parameters
having some
Example code for the function paran
function for accepting a function with
to use setTimcout
We will now discuss following synta
passed to setTimeout along with parameters has
The function that will be milliseconds,parameter1,paraneter2,
setTimeout(function name, delay in
.);

Timer2.js
console.log('Greeting message will be displayed soon..");
var myfun = (user) =>{
console log('Good Morning "+user);

setTimeout(myfun, 1000, Ankita');

Output

Command Prompt X

b:\WodeJSExamples>node timer2.js
Greeting message will be displayed soon...
Good Morning Ankita

D:\NodeJSExamples>

This function schedules the immediate execution the callbach


of
2) setlmmediate):
function after I/O event.
The syntax is
setImmediate() =>{
1/function body

We don't need to pass any time interval to this method. The first argument is the function
to execute. We can also pass any extraarguments to this function.
This method will execute a function right after the next code block which is present afte

the setlmmediate function.


For example -
console.log(Started!I),
setImmediate() =>{
consolelog("Now Executing setImmediate Block....");

TECHNICAL PUBLICATIONS an
up-thrust for knowledge
Full Stack Web Development 2- 23 NODE JS

console.log("Taski"): Note that these console.log staternents will


console.log("Taks2'): execute first and then immediately after that
the setimmediate function will execute.

Output

Comand Prompt

D:\NodeSExamp les >node timer4.js


started I
Taski
Taks2
Now Execut ing setImnediate Block....
D:\ModeJSExamp les>

3) setInterval) This function helps to execute a task in a loop after some time interval.
:

This function has the same syntax as that of setTimeout.


Syntax
timerld = setInterval(func|code, (delayl, [arg1], (arg2]....)
For example
var myfun = () =>{
console.log("Hello"):
}:
setInterval(myfun,1000);

Output

Command Prompt

p:\Wode)SExamples>node timer3. js
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
D:\ModeJSExamples>

TECHNICAL PUBLICATIONS". an up-thrust for knowiedge


Ful Stack Web Development 2-24 NODE s

The above code present inthe function myfun gels executed after every 1000 millisccond.
To break this program nunning in a loop we have to press controlte.

2.9 Callbacks
What is callbacks ?
Callbacks is a function which is usually passed as an argument to another function and u

usually invoked after some kind of event.


How it works ?
The callback function is passed as an argument to another function. When particular ct
enm

occurs then only it is invoked.


By the time callback function is executing another task gets executed.
Hence execution of callbacks is asynchronous execution.
Example Code
Step 1:Create a simple text file named "myfile.txt" as follows
myfile.txt
How are you?
Jack and Jil went up the hill,
to fetcha glass of water

Step 2: Create a JavaScript file(.js) that contains the callback function


callbackDemo.js
var fs = require(fs");
console.log(Serving User1)

fs.readFile(myfile.tt, function (ert, data) {


if (err) return console.error(err);
console.log("*** Contents of the Fle are.****);
cOnsole.log(data.toString()}:

console.log('Serving User2"):
console.log"Serving User3');
console log(Good Bye!l!");

Output
D
NodeJSExAnples>node callbackDemo.js
Serving User1
Serving User2
Serving User3
Good Byel!!

TECHNICAL PUBLICATIONS- an up-thrust for knowtedge


Full Stack Web Development 2- 25 NODE JS
***Contents the File are.***
of

How are you?


Jack and Jill went up the hill,
to fetch a glass of water

Program Explanation :
In above program.

) We have to read a file named myfile.trt. but while reading a file it should not block the
Cxccution of other statements. hence a call back function is called in which the file is
read.

2) By the time file gets read, the remaining two console functions indicating "Serving user
T" and "Serving user 2" are not blocked. rather they are executed, once the contents are
read in the buffer, then those contents of the file are displayed on the console.

Review Question
1. Explain the callbacks in node js wih suitable example.

2.10 Harndling Data /0


2.10.1 Buffers
Buffer is class that allows us to store raw data similar to arrays.
• It isbasically a class that provides the instances for storing the data.
• Itis a global class so we can use it without any need of importing a buffer module.
Creation of Buffer

Creating a buffer is very simple. For example


var buffer = new Buffer(10);
This willcreate a buffer of 10 units.
Similarly we can create a buffer as follows
-

var buffer = new Buffer([1,2,3,4,5], "utf8");


The second parameter which we have passed here is encoding scheme. It allows various
encodings such as utf8(this is default one), ascii,ucs2,base64, or hex.

Writing to Buffer

The syntax for writing to the buffer is

write(stringl,offset]. l.length||,encodingl)

TECHNICAL PUBLICATIONS-an up-thrust for knowledge


Full Stack Web Development 2-26 NODE
JS
where
string : It is the string to be written to the buffer.
offset : It is the index from where we can start writing. The default value is 0.
length : It indicates the number of bytes to be written to the buffer.
Encoding: It indicates the desired encoding. The default one is utf8".

Example Code
Following is a simple node js program that shows how towrite data to the buffer.
BufferExample.js
var buffer = new Buffer(50):
buffer.write(Good Morning ):
console.log (buffer.toString(utt8):

Output
GoodMoming
Program Explanation : In above program,
We have used write method for writing to the buffer. For displaying the string written to

the buffer we have to use toString method along with the encoding scheme.
Reading from Buffer

The syntax for reading from buffer is as follows -


toString (lencodingll.start]Lend])
where
encoding: It indicates the encoding scheme.The default one is "utf8".
start : Beginning index is indicated by this value. The default is 0.
end : Ending index is indicated by this value.

Example Code
var buffer = nevw Buffer(50);
buffer.write(Good Morning');
console.log(buffer.toStringutfB);

2.10.2 Streams
Stream can be defined as objects that reads data from source or writes the data to
destination in continuous fashion.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


FullStack Web Development NODE JS
2- 27

The stream is an EventEmitter instance that emits several events. Following are the events
that occur during stream operations -
1) data : This event is fired when we want to read the data from the file.

2) end :
When there is no more data to read then this event is fired.
3) error : If any error occurs during reading or writing data then this event is fired.

4) finish :
When data is completely flushed out then this event occurs.
There four types of streams,
1) Readable : This stream is used for read operation only.
2) Writable : This stream is used for write operation only.
:
3) Duplex This type of stream is used for both read and write operation.
4) Transform : In this type of stream the output is computed using input.

Write Operation

The steps that are followed to write data to the stream using node.js are as follows -
Step 1: Import the file stream module fs using require.
Step 2: Create å writable stream using the method createWriteStream.
Step 3 : Write data to the stream using write method.
Step 4: Handle the events such as finish or error(if any)
Following Nodejs script shows how to write data to the string,

writeStreamExample.js
var fs = require("fs");
var str ="This line is written to myfile"

var ws = fs.createWriteStream('sample.txt');
ws.write(str utf8);
ws.end();
Console.log("The data is written to the file..."):

TECHNICAL PUBLICATIONS® - an up-thrust for knowiedge


Full Stack Web Development 2-28
NODE
JS
Output

G Command Prompt

D:\NodeJSExamples>node writeStreamExample.js
The data is written to the file...

D:\NodeJSExamples>type sample.txt
This line is written to myfile .

D; \NodeJSExamples>

The above code is simply modified to handle the error event as


follows -
var fs = require("s");
var str= This line is Written to myfile";
var ws = fs.createWriteStream('sample.txt'):
ws.write(str, utf8'):
ws.end0:
console.log("The data is written to the file..."):

ws.on(error, function(err) {
console.log(err.stack);
D:

Read Operation

For reading from the stream we use createReadStream. Then using the
data event the data
can be read in chunks.

Example Code
var fs = require("fs);
var str =
var rs = fs.createReadStream('sample.txt');
TS.setEncoding("utf8"):

//handling stream event 'data'


TS.on(data',function(chunk) {
str += chunk:

TECHNICAL. PUBLICATIONS-
an up-thrust forknowledge
Full Stack Web Development NODE JS
2- 29
//handling stream event 'end'
rs.on('end'.function(){
console.log(str)

//handling stream event 'error


rs.on('error,function(err){
console.log(err.stack);

Sample.txt
This line is written to myfile

Output

G Command Prompt X

D:\NodeJSExamples>node readStreamExample.js
This line is written to myfile
D: \NodeJSExamples>

Pipe Operation

The pipe operation is a kind of operation in which output of one stream acts as an input of
another stream.
There is no limit on pipe operation that means, all the output of one stream can be fed as
input to input to another stream.
Following are the steps used for using the pipe operation in your node.js program -

Step 1: Import the fs' module using require.


Step 2: Create readable stream using createReadStream function.

Step 3: Create writable stream using createWriteStream function.


Step 4:Use the pipe() function for passing the data trom readable stream to writable stream.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 2- 30 NODE
Js
-
Following example shows the use of pipe operation

pipeExample.js
var
fs require('fs");
var rs fs.createReadStream(input,.txt');
rs.setEncoding(utf8"):
var ws = fs.createWriteStream('output.txt);
rs.setEncoding(utf8");
rs.pipe(ws):
console.log("Data is transfered from 'input.txt' to 'output.txt):

Output

A Command Prompt

b:\ode35Examples>node pipeExample.js Execution of


program
Data is transfered from 'input.txt to "output.tt
D:\ode)SExamples>type input.txt Display of input.txt
Hello friends,
Node.js is really amazing.
Really enjoying it.
D:\Node JSExanples>
D:Wode)SExamples>type output. txt Display of output.txt
Hello friends,
ode.js is really amazing.
Really enjoying it.
p:Viode}SExamples>

2.10.3 File System


Filesystem fs is implemented in the node.js using require function.
var fs = require("fs');
The common operations used with the file system module are -

1, Read file 2. Create file 3. Update file 4. Delete file

1. Read Operation
The read file operation can be performed synchronously or asynchronously.
For reading the file synchronously we use readFileSync method. And for reading the 1

synchronously read File


Normally while reading the file using asynchronous form we use callback function as
last parameter to the readFile function. The form of this callback function is,

TECHNICAL PUBLICATIONs- an up-thrust for knowledge


Full Stack Weh Development 2-31 NODE JS

function(err, data)

I/function body

Example code
var fs = require("fs"');
fs.readFile('input.txt', function(ert,data){
if(err)
console.log(err);
console.log(data.toString());

input.txt
Hello friends,
Node.js is really amnazing.
Really enjoying it.

Output

Gs Command Prompt

D:\NodeJSExamples>node readFileExample.js
Hello friends,
Node.js is really amazing.
Really enjoying it.
D:\NodeJSExamples>

Similarly we can read the file synchronously using following command -

readFileExample.js
var fs require(fs");
var data = fs.readFileSync(input.txt):
console.log(data.toString():

2. Create File Operation


We can create an empty file using the command open)

Syntax
Lopen(path, flags|,mode),callback)

TECHINICAL PUBLICATIONS. an up-thrust for knowedge


FullStack Web Development 2-32 NODE
JS
where
path :
It is the path of the filename.
That means r is open file
flag: It indicates, the behaviour
on opening a file. forreading.
or w+" means open a file for both
w" is for writing, rs" is for synchronous mode, "rt"
and write purpose and so on.
mode : It indicates readable or writable mode.
Callback : It is basically a function which has two arguments(err,data)
Example Code
var fs = require("fs"):
fs.open(myfile.txt!, w, function(en,fle){
if(err)
console.log(err)
console.log(File created!!):

3. Update / Write File Operation


For writing to the file two operations are used most commonly -
1. appendFile) and 2. writeFile)

The appendFile) method is used to write the contents at the end of the specified file.
Example Code
var fs = require(fs");
str = "This line is written to the file":
fs.appendFile(myfle.txt, str,function{er){
if(err)
console.log (err)
console.log(File appended!!!');

Output

Command Prompt
X
D:\NodeJSExamples>node appendFileExample.js
File appended!!!.
D:\NodeJSExamples>type myfile.txt
This line is written to the file
D:\Node]SExamples>

TECHNICAL PUBLICATIONS® -
an up-thrust for knowledge
Full Stack Web Development
2-33 NODE JS

The writeFile) method is used to write the contents to the file

Example Code
var fs = require("fs");
str = "This line is replacing the previous contents";
fs.writeFile('myfile.txt, str,function(er){
if(err)
console.log(err)
console.log(File Writing Done!!);
});

Output

cN Command Prompt X

p:\NodeJSExamples>node writeFileExample.js
File Writing Done!!!
D:\NodeJSExamples>type myfile.txt
This line is replacing the previous contents
|D:\NodeJSExamples>

4. Delete File Operation


To delete the file, we use unlink) method.

Syntax
unlink(path, callback)

where
path: Is a path of the file to be deleted.
callback :It is a callback function with the only one argument for 'error'.

Example Code

var fs = require("fs")};
fs.unlink('myfile.txt',function(err){
if(err)
throw err;
console.log("File is deleted!!!");
});

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 2-34 NODE
JS
Output

C Command Prompt

D:\NodeJSExamples>node deleteFileExample.js
Deleting a file
File is deleted!!!
D:\NodeJSExamples>type myfile.txt
The system cannot find the file specified. Checking if file gets deleted or not.
D:\NodeJSExamples>node deletefFileExample.js
D:\NodeJSExamples\deleteFileExample.js:4
throw err; Again trying to delete a deleted
file, hence exception is thrown.

ENOENT: no such
[Error: file or directory, unlink 'D:\NodeJSExamples\myfile.txt'] {
errno: [33m-4058+[39m,
code: +[32m'ENOENT'+[39m,
syscall: +[32m'unlink'+[39m,
path: +[32m'D:\ \NodeJSExamples\ \myfile.txt'+[39m

D:\NodeJSExamples>

Review Question
1. With necessary source code, explain how to use file I/O operations in node.js.

2.11 Implementing HTTP Services in Node.js


2.11.1 URL Object
URL is a unique identifier that provides a way to access information from remo
computers, like a web server and cloud storage.
HTTP server makes use ofURLS to handle the requests from clients.
• Basic components of URL are as follows -
https://www.technicalpublications.in:443/products/textbook/97893889180800
5?Pr_prod_start-description#myorder

TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development 2-35 NODE JS

https:// www. technicalpublications. in 443 /textbook/97893889180800-5 Pr_prod_strat=description #myorder

Protocol Subdomain Hostname Port nunber Pathname Query string Query string Hash
separator

1) Protocol : This is the request protocol used by the client while making the request. The
popular protocols in web-based applications are http and https which display the page
in HyperText(HTML) format. Some other protocols are - FTP i.e. file transfer protocol
which is used for file transfer, SMTP i.e. Single Mail Transfer Protocol which is used
for sending emails.
2) Subdomain : It is a specific type of resource to be delivered to the client. The
subdomain www is a general symbol for any resource on the web.
3) Hostname : The host name identifies the host that holds the resource.
4) Port number : A port number specifies the type of service that is requested by the
client, since servers often deliver multiple services. Some default port numbers includes
80 for HTTP and443 for HTTPS servers.
5) Pathname It specifies the exact location of the web page, file or any resource that the
:

user wants to access.


6) QueryString : The query string specifies the parameters of the data that is being
queried from a website's database. Each query string is made up of a parameter and a
value joined by the equals (-) sign. In case of multiple parameters, query strings are
joined using the ampersand (&) sign. The parameter can be a number, string, encrypted
value or any other form of data on the database.
7) Hash : It is optional and always appears at the end of the URL. It indicates a specific
location within a page such as the id' or name' attribute for an HTML element.

2.11.2 Query String and Form Parameters


a
The query string specifies the parameters of the data that is being queried from website's
database. Each query string is made up of a parameter and a value joined by the equals (=)
sign.
parse the query
The query string and form parameter are just like key-value pairs. To
string in order to obtain the values that are pased to it, the querystring.parse) method is
used.
Syntax
querystring.parse( qrystr[, Sep[, Eq[, options]]) )

where,

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 2-36 NODE
JS
qrystr :It is a string that specifies the URL qucery to be parsed.
: It is a string that specifies the substring used to delimit the
Sep key and value pairs in dl
specified query string. The default value is &".
:It is a string that specifies the substring used to delimit
Eq keys and values in tha
specified query string. The default value is "=",
Options:It is an object which enables us to change the function's belhavior with respcct o
the maximum number of keys and percent-encoded characters.

Example Code
const querystr= require'querystring");
var str = "User=admin&password=pass1234";

/ calling the parse funtion to obtain the values


console.log(ParsedObject: "querystr.parse(str))

Output
PS E:\NodeJSExamples\QueryStringDemo>
node app.js
Parsed Object: [Object: null prototype] {User: 'admin', password:
pass1234}
2.11.3 Request, Response and Server Object
The web module is mainly controlled by a web server
that handles the requests and
provides the responses. These requests and responses are handled
by HTTP(Hyper Text
Transfer Protocol) protocol.
The user submits the request using a web browser. Thus the communication between web
server and web browser is handled
by HTTP protocol. Following steps. explain this
communication
When a user submits a request for a web page, he/she is actually
demanding for a page
present on the web server.
When a web browser submits the request for a web page,
the web server responds to thS
request by sending back the requested page to the web browser
of the client's machine.
Request for
web page
Web browser Serves the Web server
web page

Fig. 2.11.1 Client-server communication

TECHNICAL PUBLICATIONs- an up-thrust for knowledge


Full Stack Web Development
2-37 NODE JS
:
Step 1 Web client requests for the desired web page by providing the IP
address of the
website.

Step 2 Theweb server locates the desired web page on the website and responds by
:

sending
back the requested page. If the page doesn't exist, it will send back the
appropriate error page.

Step 3: The web browser receives the page and renders it as required.

The request and response objects of the HTTP module in Node.js are the important
objects of client server communication.
Following are important objects that we will learn in this section -

1. http.ClientRequest 2. http.ServerResponse 3. http. IncomingMessage 4. http.Server

2.11.3.1 The http.ClientRequest Object


This object is useful to monitor the in-progress request.
• The ClientRequest object is used to monitor and handle the response from the server.
• For implementing the ClientRequest object the call to the http.request() is made. The
-
syntax to this method is as follows

Syntax
http.request(options,callback)

Parameters
1) options parameter is an object which is responsible for defining how to open and send
the client HTTP request to the server. Various options that can be specified while
creating ClientRequest are as follows -
Property Purpose
host The domain name or IP address of the server to which the request is
made. Default is localhost.

port The port number. Default is S0.

method It is the HTTP request method, it can be GET, POST.CONNECT.


Default is GET.

path A string specitying the requested resource path. Default is /

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
Full Stack Web Development 2- 38
NODE
JS
callback parameter is callback function which is called after the request is sent
a
2)
tothe
server. Then this function handles the response obtained fromthe server(note
hat itisa
callback function).
Example Code
var http= require(http");
var server = http.createServer(function(request,response) {
I/Creating a response
response.writeHead(200.(Content-Type": text/plain'"});
response.end("Hello, This text is displayed as a response to the clhent request!!");

server.listen(8082,() =>{ Options i.e. the first parameter of.


var options = { ClientRequest object is defined here.
hostname: localhost,
path: '/,
port: 8082.
method: POST

var req= http.request(options, function(response){ response is obtained with the help of


var resuit =": ClientRequest object
response.on('data function(chunk){ ClientRequest object is implemented
result+=chunk, using 'request' method
}:
Tesponse.on('end,function(){
console.log("Response using ChentRequest object is as follows.");
console.log("String: "+result):
Displaying the response on the
console.log('Method:+ req.method);
Console.

zeq.end(0:

Output

Open the terminal window or command prompt and get the output on the console
follows -

PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL

PS E:IodeJSEXamples\clierntRequestDemo> node app.js


Response using clientRequest object i as follows.,,
String: Hello, This text is displayed as a response to the client request!!!
Method:POST

TECHNICAL PUBLICA TIONS an up-thrust for knowledge


Full Stack Web Development
2-39 NODE JS

Now open some suitable web browser such as Mozilla Firefox or Google Chrome
and typc the localhost:8082 as URL. It is illustrated by following screenshot

localhost.8082 +

C O localhost:8082

Other bookmarks

Hello, This text is displayed as a response to the client request!T!

2.11.3.2 The ServerResponse Object


When the request event is received then the ServerResponse object is created
internally.
The ServerResponse object is passed as a second parameter to the requestListener
function.
This object makes use of WVritable Stream for writing the data back to the client.
• Following are some properties and methods that are used by ServerResponse objects to
build and send header, write the data or to send the response.
addTrailers() This method adds HTTP trailing headers.

getHeader() This method is to get the value of an HTTP header that has been set in the
response.

removeHeader() This method removes the specified HTTP header.


-
setStatusCode This property allows us to specity the status response code. For instance
response.statusCode = 500

setTimeout() Sets the timeout value of the socket to the specified number of milliseconds.

write() Sends the text, or a text stream to the client.

TECHNICAL PUBLICATIONS- an up-thrust for knowedge


Full Stack Web Development 2- 40 NODE
J
writelHead) Sends the status and response hcaders to the clicnt.

close This property is uscd to when to the conncction to the client is closedIprior
to the response.end) method.

end() This method is an indication for the server that the response is now
complete.

Example Code
Node.js has a built-in module named http which allows us to transfer data over the Hper
Text Transfer Protocol(HTTP).We will build a web server using http module.

WebModuleExample.js
var http= require('http);
var server = http.createServer(function(request,response) {
response.writeHead(200,("Content-Type": "text/plain"});
response.end(Welcome to this Web Module Application!"):

server.listen(8082);
console.log("Server is running on port 8082 port...");

Output

Step 1: First of all open the command prompt and type the following command.

Command Prompt - node WebModuleExam..

D:\NodeJSExamples\HttpApp>node WebModuleExample.js
Server is running on port 8082 port...

Step 2 :Now open some suitable web browser such as Mozilla Firefox or Google Chrome an0
type the localhost:8082 as URL. It is illustrated by following screenshot

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Developent 2- 41 NODE JS

localhast.8092

O localhost:A082

Welcome to this Web Module Application ! II

: In
Seript Explanation above given Node js seript.
1) We have imported http module.
2) The http.createServer) method includes request and response parameters which is
supplied by Node.js.
a response, first it sets the response header using the writeHead) method and
3) Tosend
then writes a string as a response body using the write() method.
4) Finally, Node.js web server sends the response using end) method. But we can directly
write the response body using the end method.
5) Using the server.listen method we can specify the port number on which our web
server is running.
6) Just refer to the illustrative output given above.

Handling various Http requests


The Http.request object is used to get information about the current Http request. The
response objeçt is used to send the response for current HTTP requests.
Following Node.js script shows how different HTTP requests are made and how to respond
to them using the response object of the HTTP module.

WebModuleExample.js
var http= require("http");
var server = http.createServer(function(request,response) {
if(request.url == "/"){
Iesponse.writeHead(200, ("Content-Type": "text/html"} );
response.write("<html><body ><h1>Welcome to this Web Module
Application! </h1></body></html>");
response.end():

TECHNICAL PUBLICATIONS an up-thrust for knowiedge


Full Stack Web Development 2- 42 NODE
JS
else if(request.url =="/About"){
response.witeHead(200,{"Content-Type': "text/html'});
response.write(" <html> <body> <h2> About Page</h2><b0dy></htmls"):
response.end();

else if(request.url ==/Contact"){


response.writeHead(200.{"Content-Type": "text/html"} ):
response.write(" <html> <body><h2>Contact Information</h2> </body> </html>":
response.end();

else
response.end("This is invalid request");

server.listen(8082);
console.log("Server is running on port 8082 port.);

Output

Command Prompt- node WebModuleExam.

|:\NodeJSExamples\HttpApp>node WebModuleExample.js
on .
Server is running port 8082 port..

We can open a web browser and get the about page by making the request using the URL
as "localhost:8082/Abou". The illustrative output is as given below -

X
localthost£032/About

f C 0 localhost:B082/About

About Page

TECHNICAL PUBLICATIONS"- an up-thrust for knowtedge


Full Stack Web Development NODE JS
2- 43
2.11.3.3 The incomingMessage Object
• The IncomingMessage object is created either by HTTP server or the HTTP client.
When this object is used at the server side, the client request is represented by the
IncomingMessage object.
• When this object is used at the client side, the server response is represented by the
IncomingMessage object.
The IncomingMessage implements Readable stream. Using this object client request
or server response is read as a streaming source.
Following are some events, properties and methods of IncomingMessage object -
headers This is an object containing the headers sent with the request/response.

Trailers This is an object containing any trailer headers sent with the
request/response.

Method It specifies the methods for request and response. The method can be GET,
POST,CONNECT.
statusCode Itspecifies the three digit status code from the server.

socket This a handle to the net.socket object used to communicate with the client
and server.

url The url string is sent to the server. This string can be parsed using url.parse)

close It is used while closing the communication.

Example Code
const http = require(http);

const server = http.createServer(reg, res)=>{


I| Accessing the IncomingMessage object
console.log(` Request method: ${req.method} ):
console.log(' Request URL: ${req.ul});

I/ Sending a response
res.writeHead(200, {'Content-Type: text/plain });

res.end(Welcome');

server.listen(8082, () =>{
console.log('Server is listening on port 8082'):

TECHNICAL PUBLICATIONS an up-thrust for knowledge


Full Stack Web Development 2-44 NODE
J$
Output

DEBUG CONSOLE TERMINAL


PROBLEMS OUTPUT

E:\NodeJSEXamples\incomingMessageDemo> niode app.js


PS
Server is listening on port 8082
Request method: GET

Request URL: /
Request method: GET
Request URL: /favicon.ico

Open the web browser and issue the address "localhost:8082", the response on the weh

page is displayed.

S localhost:8082

O localhost:8082
Other bookmarks

ielcoe

Program Explanation : In above program,


1) Using the createServer), the HTTP server is created.
2) When the client sends the request to the server, the server creates an

'http.IncomingMessage' object, which is passed as the reg parameter to the servers


request handler function.

3) Then using the reqparameter we have read the method and url properties.
4) Similarly we can send the response to the client using WriteHead) and end) methou
of the http.SeverResponse. object which is passed as a res parameter to the requ
handler function.
5) Thus http.IncomingMessage takes part in both client request and server response.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 2- 45 NODE JS
2.11.3.4 The http.Server Object

The HTTP module can create an HTTP server that listens to server ports and gives a
response back to the client. The createServer() method is used to create an HTTP server. This
method returns the server object. Once the server object is created then begin listening on it
by calling the listen() method on the server object.
For example -

app.js
var http =require("http");
var server = http.createServer(function(request,response) {
response.writeHead(200,("Content-Type": "text/plain"} ):
response.end("Welcome to this Web Module Application!!!"):

server.listen(8082);
console.log("Server is running on port 8082 port...");

Review Questions
Explain the concept of query string and formparameters.
2. Explain the htp.clientRequest object in Nodejs with suitable examples.
3. What are the properties and methods of http.ServerResponse ?

2.12 Two Marks Questions with Answers


Q.1 What is Node.js ? Give its uses.
Ans. : Node JS is an open source technology for server. Using Node.js we can run JavaScript on
server.
-
It can perform various tasks such as
1)
lt can create, open, read, delete, write and close files on the server.
2) It can collect form data.

3) It can also add, delete, modify data in databases.

4) It generate dynamic web pages.


Q.2 What is NPM ?
Ans. : The NPM stands for Node Package Manager. NPM consists of two main parts :

1) A CLI (command-line interface) tool for publishing and downloaing packages,


2) An online repository that hosts JavaSeript packages.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 2-46
NODE
Node.js.
Explain the use of 'cluster' module
in
Q.3
Ans. : The cluster module helps in creating
a
child process. Both the main and
child proceK«er
can run simultaneously and share the same server port.

Explain the console.log statement in Node.js with suitalble example


Q.4
Ans. : console.log((datal|,..) : t is used for printing to stdout with newline. This
function
a
printf statement in C. ca
take multiple arguments similar to

For example -
var emp name = Ankita.
emp depts =
dept1: Sales, dept2: 'Accounts

console log (Name: %s+\n+ Departments: %j,emp name, emp depts);

Q.5 What is EventEmitter ?


Ans.: The emitter objects performs following tasks

1) It emits named events.

2) Registed and unregisted listener functions.


Basically EventEmitter is a class which can be used to
raise and handle custom events
Q.6 What is the purpose of addListener method ?
Ans. : Adds a listener to the end of the listeners array for the
specified event. No checks are
made to see if the listener has already been added.
Q7 Explain the setMaxListener and getMaxListener
methods of Node.js.
Ans.:
1) setMaxListeners(int) : This method sets the number of
listeners to the particulareve
a
defauit, maximum of 10 listeners can be
registered for any single event.
setMaxListeners() o
2) getMaxListeners) : I1 will return
the max listeners value set by
default value 10.

Q.8 Explain the setTimeout function


in Node.js with suitable
example.
Ans.: This function is used to set one time milliseconds.
callback afier delaying by Some
Syntax
setTimeout(function,delay
in millissconds)

Example Code
console.log(Task1;
serTimeout(function) {console.logTake2:Executing
Consolelg(Tark3');
After 4 seconds") },4000);

TECHNICAL PUBLICATIONS-
an up-thrust for
knowledgo
NODE JS
Full Stack Web Development 2- 47
Q.9 How callback functions are handled in Node.js ?
Ans. :
Callbacks is a function which is usually passed as an argument to another function and it
is usually invoked after somc kind of event.
var fs = require("s'):
console.log('Serving User 1")
fs.readFile('myfile.txt', function (err, data) (
|if (err) return console.error(err):
Console.log("*** Contents of the File are..***"):
console.log(data.toString());

console.log("Serving User2");
console.log("Serving User3"):
console.log("Good Bye!!"):
Q.10 What is pipe operation in Node.js.

Ans. :
The pipe operation is a which output of one stream acts as an input
kind of operation in

means, all the output of one stream


of another stream. There is no limit on pipe operation that
can be fed as input to another stream.
|pipeExanmple.js
var fs = require("fs");
var rs fs.createReadStream('input.txt');
rs.setEncoding('utf8");
var ws = fs.createWriteStream('output.txt');
rs.setEncoding('utf8");
rs.pipe(ws);
Console.log("Data is transfered from 'input.txt' to 'output.txt "):

Q.11 What is QueryString?


a
Ans. The query string specifies the parameters of the data that is being queried from
:

a
website's database. Each query string is made up of a parameter and value joined by the
are joined using the ampersand
equals (F) sign. In case of multiple parameters, query strings
or any other form of data on
(&) sign. The parameter can be a number, string, encrypted value
the database.
Q.12 Explain the use of ClientRequest object.
server.
Ans. : The ClientRequest object is used to monitor and handle the response from the
For implementing the ClientRequest object the call to the http.request) is made. The syntax
-
to this method is as follows
http.request(options,callback)

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


2- 48 NODE
JS
Full Stack Web Development

Q.13 Explain the incomingMessage object. server or the HTTP


created either by HTTP client.
• The IncomingMessage object is
Ans.: request is represented by thc
server side, the client
When this object is used at the
IncomingMessage object.
the server response is represented by ih.
When this obiect is used at the client side,
IncomingMessage object. request or
TheIncomingMessage implements Readable stream. Using this object client
source.
server response is read as a streaming

TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
UNIT III

3
Syllabus
MONGO DB

Understanding NoSQL and MongoDB - Building MongoDB Environment - User accounts - Access
control - Administering databases - Managing collections Connecting to MongoDB from Nodejs
-

simple applications.

Contents
3.1 Understanding No SQL and MongoDB
3.2 Building MongoDB Environment
3.3 User Accounts
3.4 Access Control
3.5 Data Types in MongoDB
3.6 Administering Databases
3.7 Managing Colections
3.8 Connecting to MongoDB from Node,js
3.9 Understanding the Objects Used in MongoDB Node,js Driver
3.10 Simple Applicaions
3.11 Advanced MongoDB
3.12 Two Marks Questions with Answers

(3- 1)
MONGO
3-2 DB
Full Stack Web Development

3.1 Understanding NoSQL and MongoDB


3.1.1 NoSQL
NoSQL stands for not only SQL.
system that store data differently than relational tables
Th
It is nontabular database
as document, key-value, wide column
axd
are various types of NoSQL databases such
graph.
and these schemas can be scaled easil.
Using NoSQL we can maintain flexible schemas
with large amount of data.

Need:
adopted for following reasons
The NoSQL database technology is usually
as a part of fundamental
1) The NoSQL databases are often used for handling big data
architecture.
structured, semi-structured
2) The NoSQL databases are used for storing and modelling
and unstructured data.
3) For the efficient execution of database with high availability, NoSQL is used.
so it scales out better than relational
4) The NoSQL database is non-relational,
databases and these can be designed with web applications.
5) For easy scalability, the NoSQL is used.

Features:
1)The NoSQL does not follow any relational model.
2) It is either schema free or have relaxed schema. That means it does not requius

specific definition of schema.


3) Multiple NoSQL databases can be executed in distributed fashion.
4) It can process both unstructured and semi-structured data.
5) The NoSQL have higher scalability.
6) It is cost effective.
7) It supports the data in the form of key-value pair, wide columns and graphs.

3.1.2 MongoDB
MongoDB is an open source, document based database. known as
noow
It is
developed and supported by a company named 10gen which is
MongoDB Inc.
The first ready version of MongoDB was released in March 2010.
TECHNICAL PUBLICATIONSan
up-thrust forknowledge
Full Stack Web Development MONGO DB
3-3
Why MongoDB is needed ?
There are so many efficient RDBMS products available in the market, then why do we
need MongoDB ? Well, all the modern applications require Big data, faster development and
flexible deployment. This need is satisfied by the document based database like MongoDB.

Features of MongoDB
1) It is a schema-less, document based database system.
2) It provides high performance data persistence.
3) It supports multiple storageengines.
4) It has a rich query language support.
5) MongoDBprovides high availability and redundancy with the help of replication.
That means it creates multiple copies of the data and sends these copies to a different
server so that if oneserver fails, then the data is retrieved from another server.
6) MongoDB provides horizontal scalability with the help of sharding. Sharding
means to distribute data on multiple servers.

7) In MongoDB, every field in the document is indexed as primary or secondary. Due to


which data can be searched very efficiently from the database.
SQL Structure Vs. MongoDB
Following Fig: 3.1.1l shows the terms in SQL are treated differently in MongoDB. In
MongoDB the data is not stored in tables, instead of that, there is a concept called collection
which is analogous to the tables. In the same manner the rows in RDBMS are called
documents in MongoDB, likewise the columns of the record in RDBMS are called fields.
SQL Terms MongoDB Terms

Databases Databases

Tables Collections

Rows Documents

Columns Fields

Fig. 3.1.1

student database as follows


-

Consider a

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


MONGO
Full Stack Web Development 3-4 DB

the form of table and to the right hand side


To the left hand side we show the database in
the database is shown in the form of collection.
Collection

"
id':527191e810c19349de860eg,
"Name":"'Ankita",
"Course":"Computer Engineering",
"Address":{ Document 1
"line1":"ILane1"
"line2" Lane2"
}

" id":557f191e810c19729de860ea,
Name Course AddressLine1 AddressLine2 "Name":"Prajkta",
"Course""'Mechanical Engineering",
Computer Lane1 Lane2
Ankita "Address":{ Document 2
Engineering
"line1":"Street1",
Mechanical "line2:"Street2"
Prajkta Street1 Street2
Engineering
Civil
Kavita Engineering Road1 Road2

id:507f141e510c19729dey60ed,
"Name":"Kavita",
Fields "Course""Civl Engineering',
+"Address":{ Document 3
"line1"Road1",
"line2":"Road2"

Fig. 3.1.2

Review Questions
1. What is NoSQL ? What is the need for it ? Enlist various feature of
NoSQL.

2 List and explain various features of MongoDB

3.2 Building MongoDB Environment


For installing the MongoDB go to the web site
https://www.mongodb.com/ry/download/community
on
Choose Software-> Community Server. The executable file gets downloaded, Click

Run to execute it.

TECHNICAL PUBLICATIONS-
an up-thrust for knowledge
Full Stack Web Development MONGO DB
3-5
Open File - Security Warning X

Do you want to run this file?

Name: .0ads\ mongodb-windows-x86_64-6.05-signed.si


Publisher: MONGODB, INC.

Type: Windows Installer Package

From: CAUsers\ DELL\Downloads\mongodb-windows-&.

Run Cancet

Always ask before opening this file

While files from the Internet can be useful, this file type can
potentially harm your computer. Only run software from
publishers you trust. What'sthe risk?

When the installation process starts following window gets popped up

D MongoDB 6.0.5 2008R2Plus SSL (64 bit) Setup

Welcome to the MongoDB 6.0.5


2008R2Plus SSL (64 bit) Setup Wizard

The Setup Wzard will install MongoD8 6.0.5 2008RPlus SSL


(64 btt) on your computer. Clhck Next to continue or Cance to
exot the Setup Wzard.

Back Next Cance!

Just click on Next button and choose the Complete option for installation. Follow the
normal procedure of installation by clicking the Next button. If you do not want to install the
MongoDB Compass(the Graphical tool of MongolDB), then simply uncheck the option.
Finally you will get following window on successful installation.

TECHNICAL PUBLICATIONS- an up-thrust for knowedge


3-6 MONGO DB
Full Stack Web Development

MongoDB 6.0.5 2008R2Pius SSL (64 bì) Setup

Completed the MongoDB 6.0.5


2008R2Plus SSL (64 bit) Setup Wizard

Chck the Antsh button to dt the Setup Wizard.

Cancel
Euck Anish

Click on Finish button, tocomplete the installation process.


In order to verify whether it is installed correctly
or not, go to command prompt window
mogod.exe version. It is illustrated as follows -
and execute the command for file's
X
CAWindows\System32)cmde

Hicrosoft Windows [Version 10.9.22621.1555] Issue this command


c) Microsoft Corporation. All rights reserved.
C:\Program Files \iongoDB\Server\6.\bin>mongod.exe version
db version, v6.0.5
Build Info:
version": "6.0.5"
"gitVersion":
"nodules":
"allocator":
,
"c9a99c120371d4d4c52cbb15dac34a36ceBd361d"

tcmalloc
If the
MongoDB is
correctly
installed
"environnent": {
then you
"distmod": "indows" will get this
"distarch": "x86 64" result
"target_arch"x86_64"

C:\Progran Files\MongoDB\Server\6.9\bin>

Environment
To set the environment variable, Open System Properties and click on

Variables

TECHNICAL PUBLICATIONS- an up-tlhrust for knowiedge


Full Stack Web Development MONGO DB
3-7

Gytem Dropertis

Computer Name Hardware Advanced System Protection


Remate
You must be logged on as an Adminigtrator to make most of
thasa changes
Perfonance
Visuaf efects proCe150r schadufing. mermar USage.
and vitual memorf

Setings

User Profles
Desktop setings related to your sign-in

Setfings

Startup and Recovery


System startup. system failure, and debugging infcormason

Setngs

EnvironmentVariables

OK Cancel pply

Envircnment Varabtes

User variables for DELL

Varnable Value
ChocolateylastPathUpdate 13255015184767214
classpath C\Program FilesJava\ydk-150.1\bn\mysqi-connector-java-5.
OneDrive C\Users\DELL\OneDrve
OneDriveConsumer CAUsers\DELL\OneDrve
Path CAUsers\DELL\AppData\Loca/\ Micccsoft\WindowsAppsCUs
TEMP C\Users\DELL\AppData\LocalTemp
TMP C\Users\DELL\AppData\ Loca\Temo

New.. Edit Delete

System variables

Variable Value
Chocolateytnstal! C\ProgramData\chocolatey
classpath CAProgram FilesJava\yak-150.1\oin\mysqt-connector-java-5.
ComSpec C\Windows\system32\cnd.exe
DriverData CWindows| System32\Drvers\DrrverData
JAVA HOME C\Program Files\Javalydk-15.0.1
NUMBER_OF_PROCESSORS 8

OS Windows_NT

New.. Edt. Deete

OK Cancel

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 3-8 MONGO DB

Then click on the path variable and set the path of MongoDB by clicking New button.
Edit environment variable

CAUsers\DELL\AppData\locaNPrograms\Python\Python3 10\Scr. New


CAUsers\ DELL\AppData\Locan prograrns\Python\ython310\
%USERPROFILE%\AppData\LocalMictosoft\ WindowsApps Edit
CAUsers\0DELL\AppData\locan programs\Microsoft VS Code\bin

CAUsers\DELL\AppData\ Roaming\npm Browse

CProgram Fites\MongoDE\Server60\bin
Delete

Move Up

Move Down

Edit text..

OK Cancel

Then simply continue clicking ok button and just come out of the environment variable
window.
Installing Mongo Shell
For working in MongoDB sheli, the shell is separately installed. For installing it, go to the
on Download button. The
website https://www.mongodb.com/try/download/shell. Click
zip

file gets installed. Just unzip this file to get the MongoDB shell installed. Then set
the

environment variable to set the path for MongoDB shel. In my case, the mongosh.exe Is
C:MongoDBSh\mongosh-1.8.0-win32-x64\mongosh-1.8.0-win32-x64\bin,
present at the path
hence I willadd the New path in the Environment variable tab as "CAMongoDBShmongos
1.8.0-win32-x64\mongosh-1.8.0-win32-x64\bin"

TECHNICAL PUBLICATIONS - an up-thrust for knowtodge


Full Stack Web Development MONGO DB
3-9

Edit envirgnment variable

CAUeerst DELL\ApnDataLccaf Progrm Pthont Pthen31 Sert

CUersDELIApnata Locan Eregrarme Pthon\ Pthon31


USEPPnOFILEAAppata Loran Mirrosafr WindoweAops
Edit
CAUsersDELIApoData Loraf PrngramsMiereett YS Code bin
CIUors\OELLAppData Poamingnom
Browse
C\Prngran Fie MongoDServer 6 bin
GMongoDEShmangosh-180-in2monigosh 160-in3
Delete

Move Up

Move Don

Edit text

OK Cancel

To verify the installation, open the command prompt and issue the command mongosh.
-
The test prompt will appear as follows

Amongosh mongodb://n27.00. X X

Current Mongosh Log ID: 644124333492e9ceOb6931f7


Connecting to: mongeib://127 9.8 :27937 TdirettannetiuntafaerzerSeletionTeauts2
Using MongoDB: 6.0.5
1.8.0

For mongosh info see: https://docs. mongodb.com/mongodb-shell/

2023-04-20T16:39:36. 203+05:30: Access control is not enabled for the database. Read and write ac
cess to data and confiquration is unrestricted

Enable MongoDB's free cloud-based monitoring service, uhich will then receive and display
metrics about your deploynent (disk utilization, CPU, operation statistics, etc).
The nonitoring data will be available on a MongoD8 website with a unique URL
accessible to you
and anyone you share the URL with. MongoD8 may use this information to nake product
inprovements and to suggest MongoDB products and deplaynent options ta vou.
To enable free monitoring, run the following comnand: db.enableFreeManitoring ()
To peroanently disable this reminder, run the following command: db.disableFreeHonitoring ()

test>

TECHNICAL PUBLICATIONS- an up-thrust for knovwledge


MONGO
3- 10 DB
Full Stack Web Development
(Graphical Tool)
Installing Mongodb Compass
MongoDBdatabase with the help of
sinmplegraplhical
handling
This tool is very useful for
user interface.
ry/dunkadeamrnty
mongodb com
Nominate

Solutions Docs
Prcng Leam
mongoDB. Cioud Softwe

Communitly Sever
open documrt databace
A fro and

Enterprise Sever
Rovanced fastues tend Secuty

Developer Tools
MongoD8
Ccrnect conhgure src work with

CompasS

MIngoDE
Ops Manager
Or-prem nageet platarn ior Morg08
MongoDE Canectors
Ees egans to you duta state

MengoDB ot pd
ofers the fierible docunent moce zlong with ad hoc queries, indexi

z0CES En analyze your data As a distributed system you get high al

a operating
Select any suitable version as per your operating system. As mine is Windows
system of 64 bit, I have chosen following option.

Available Downloads

Veron
1.260 (Stable)

Paiorm
Windows 64-bit (7+) (MS)

Pakaze

pownoad Copy Link

Documeritaton
Archrved reieases

TECHNICAL PUBLICATIONS.
an up-thrust for
knowledge
Full Stack Web Development MONGO DB
3- 11

Click on the Download button. The exe file will get downloaded. Double click the installer
file which is downloaded in your PC and the installation process for Mongo DB Compass will
start.
MongoDB Compass Setup X

Welcome to the MongoDB Compass


Setup Wizard

The Setup Wizard rill install MongoDB Compass on your


computer. Click Next to continue or Cancel to et the Setup
Wizard.

aack. Net Cancel

Simply go on clicking Next button and then click on the install button on the subsequent
window. Finally you willget the installation completion screen.

MongoDB Compass Setup X

Completed the MongoDB Compass Setup


Wizard

Clhck the Finsh button to ext the Setup WIzard.

Back Einish Cancel

TECHNICAL PUBLICATIONS- an up-thrust for knowedge


Full Stack Web Development 3- 12 MONGO DB

Windows, locate
Just click Finish button. Now, click the Start button
of
MongobB
Compass Application and simply click it to start the GUI for Mongo DB. You
will ge
following GUI
•MonoE Compas -Connect

Conet iew Hetp

NeConrecon
Fvorites New Connection RRE
F in connection fields indhvidualy
Recens

Paste your connection string (SRV or New to Compass end dont have a cluster?
Standard 0) tyou don) alteady have a chster, vou can
create ons far free using MongoB Atlas.
e.g mongorb +<dhsemae Dastwordéchs
CREATE FREE CLUSTER

Conect
How do I find my connection string In
Atias?
!yx hve an Atlas custot, go 1othe
Cluster
Vew Cck the Connect button for the cluster
to wtch you wsh to connect.

Spe cxage

How do i format my connection string?

SegaToe

If we click the connect button then we get following screen


MongoDE Compass- locahost27017

Connec Viess ielp

Local Dstabases Pertorraance

CREAIEDRRSE
FAVORTE

Database Name Storage Size Collections Indexes


SHOST

localhost:27017
CUUSTER adrmin 20.0K8
Standalone

config 24.0KB 2
MangoDB444 Communty

koca! 20.0KB
admn
Sconfig

onsinetB

TECHNICAL PUBLICATIONS- an up-thrust for


knowledge
Full Stack Web Development MONGO DB
3- 13

3.3 User Accounts


MongoDB stores the information of all the users including name, password and user
authentication in the system.
Using MongoDB shell command we can create the user accounts. Using such user accounts
we can rcad and write to the databases.

The most commonly used operations are


1. List the users
2. Create the user accounts
3. Remove the users
Let us discuss them one by one.

3.3.1 Listing Users


User accounts are stored in db.system.users collection of each database. There exists an
object named User which contains the fields like id, user, pwd and roles.
For listing the users in the system, switch to admin database and then use show users
command.

mongosh mongodb://127.0.0. X X

test> use admin


switched to db admin
admin> show users

admin>
admin>

As no user is created, it is showing empty.


Another query is using find). The db.system.users.find(0 returns a cursor object. Then
using count) method we can obtain the total number of users present in the system. For
-
example

.
TECHNICAL PUBLICATIONS an up-thrust for knowiedge
Full Stack Web Development 3- 14 MONGO DB

mongosh mongodb://127.0.0. X X

test> use admin


switched to db admin
admin> curs0r = db.system.users.find)

admin> cursor.count)
admin>

3.3.2 Create User Accounts


The user accounts are created using the createUser) method.
Syntax
db.createUser(user, witeConcern)
Parameters
user: is a document with authentication and access information
about the user to create.
writeConcern :This document represents the level of write concern for creation operation.
The user document has following fields
Name Description Type
User The name of the new user.
string
pwd The user's password. The pwd field is not required if we string
run db.createUser() on the Sexternal
database to create
users who have credentials stored externally to
MongoDB.
customData Any arbitrary information. This fieldcan be used to store document
any data an admin wishes to associate with this particular
user. For example, this could be the user's full name or
employce id.

roles The roles granted to the user. Can specify an empty array array
I] io create users without roles.

TECHNICAL PUBLICATIONs- an up-thrust for knowledge


Full Stack Web Development MONGO DB
3- 15

The role can be specified as


(role: "<role>", db:"<database>"
-
For example

mongosh mongodb://127.0.C X

admin> use test


switched to db test
test> db.createUser(
user: "parth"
pwd: "Parth123",
roles: []
}
D;
{ 1 }
ok:
test>

Now to test, if the user named Parth is created or not, we issue the show users command
at the MongoDB shell.

X
l mongosh mongodb://127.0.0.

test> show users

_id: 'test. Parth',


userId: new UUID("59bb3031-f90f-4dle-9749-801469e4e645"),
user: Parth
db: test'
roles: [], 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
mechanisms: [
}

test>

The above user is created without any role. But we can assign the role to the user during
the createUser command.

TECHNICAL PUBLICATIONS. an up-thrust for knowledge


Full Stack Web Development 3- 16 MONGO
DB
Creating the user with roles
Following is the list of ssome commonly used roles that can be assigned to the USer aCCount.
Role Description
read Allows the user to read data from any collection within
database.
readAnyDatabase It is similar to read except on the local and config databascs

readWrite This role provides all the privileges of the read role plus the
ability to modify data on all non-system collections.
dbAdmin This role allows the user to read from and write to the database
as well as clean, modify, compact, get statistics profile and
perform validations.
dbAdminAnyDatabase Same as dbAdmin except for all databases.

userAdmin This role allows the user to create and modify user accounts on
the database.

userAdminAnyDatabase Same as userAdmin except on the local and config databases.

-
For example
db.createUser(
{

user: "sysAdmin',
pwd: "pass123",
roles:['readWrite',"dbAdmin"]

):

Following screenshot represents how to create user with role.

mongosh mongodb:t/127.0.0. X

test> db.createUser(
user: sysÅdmin",
pwd: "passl23"
roles: "readwrite", "dbAdmin"]

{ ok:
test>

TECHNICAL PUBLICATIONs- an
up-thrust for knowledge
Full Slack Web Dovelopment MONGO DB
3- 17

3.3.3 Remove Users


For removing the user, the db.dropUser() is use.

Syntax
db.dropUser(username)
For cxample

mongosh mongodb://127.0.0. X

test> db.dropUser("sysAdmin");
}
{ ok:
1

test>

By above command the user named "sysadmin" is removed.

Review Questions
Explain how to create users in MongoDB? Also enlist and explain various roles of the

USers.
2. How will you remove the user in MongoDB ? Explain.

3.4 Access Control


User exists in context of a single database. MongoDB provides authentication and
authorization at database level.
• For basic authentication purposes, MongoDB stores user credentials inside a collection
called system.users in each database.
The admin database does not have any users assigned to it.
The User administrator account provides the ability to create user accounts in the admin
and other databases.

3.4.1 Creating a User Administrator Account

For configuring the access control, the first step is to implement User Administrator
account.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 3-18
MONGO
User Administrators create users
and create and assigns roles. U
User Administratog
A

can grant any privilege in the database and can create new ones.
In a MongoDB deployment, create the User Administrator as the first user.
But
not manage the database.
Syntax for creating the user administrator account is as follows -
use admin
b.createUser(
user:"<usemame>",
Pwd:"<password>"
Roles: ["userAdminAnyDatabase]})
For example

mongoshongod270D X

test> use adnin


suitched to db adnin Creating admin user in
adin> db.createUserl the admin datababase
user:"sysadnin",
prd:"systeni23,
{
roles: ["userAdninAnyDatabase ]})
ok: 1 }
adain> shor users Displaying the users
from the admin
id: ainin.sysadnin"
userId: nez UUID("b626bedd-42ca-4880-97dc-488dea7d4011"),
user: 'sysadnin,
db: adnin',
roles: I{ ole: 'userAdrinAnyDatabase', db:
mechanisns: [ SCRAN-SHA-2, SCRAM-SHA-2561 )admin'
),

admin>

Note that the administrator user is now


sysadmin with password system 123.
We can name ard
authenticate the admin database using
db.auth command with user
password options. For example

ongot mongolecede x X

test> use adsin


suitcihed to db adnin
2dmin> do.auth(sysadnin",'systen123"):
{
c: 2}
ainin>

TECNCAL PUBLCATIONS-an
up-thrust for knoatedge
MONGO DB
Full Stack Web Development 3-19

Ifa wrong password is uscd then it gives the authentication error

mongosh mongodb://<crede X X

admin> use admin


already on db admin
admin> db. auth ("sysadmin", "pass123");
MongoServerError: Authentication failed.
admin>

3.4.2 Creating Database Administrator Account


For creating a Database Administrator account the createUser method is used. The assign
the roles such as readWriteAnyDatabase, dbAdminAnyDatabase, clusterAdmin.
-
For example

mongosh mongedb://<crede
X

test> use admin


switched to db admin
admin> db.createUser(
user: "dbAdmin"
pwd: "password123",
"dbAdninAnyDatabase", "clusterAdnin"]
,

roles: ["readWriteAnyDatabase"

{
ok: 1}
admin>

We can use this user in MongoDB shell to administer the database.

Review Question
account in
1. Explain with suitable example how to create databaIse administrator
MongoDB ?

3.5 Data Types in MongoDB


MongoDB.
Following are various types of data types supported by
numerical value.
1) Integer : This data type is used for storing the
true or
2) Boolean :
This data type is used for implementing the Boolean values i.e.
false.
TECHNICAL PUBLICATIONS- an up-thrust lor knowledge
Full Stack Web Development 3-20 MONGO DB

3) Double : Double is used for storing floating point data.


4) String: This is the most commonly used data type used for storing the string value
5) Min/Max keys : This data type is used to compare a value against thc lowest .
highest BSON element.
6) Arrays : For storing an array or list of multiple values in one key, this data tvne :
used.
7) Object : The object is implemented for embedded documents.
8) Symbol : This data type is similar to string data type. This data type is used to slore
specific symbol type.
9) Null: For storing the null values this data type is used.
10) Date : This data tvpe is used to store current date or time. We can also create our
own date or time object.
11) Binary data : In order to store binary data we need to use this data type.
12) Regular expression : This data type is used to store regular expression.

Review Question
1. Give various data npes used in MongoDB.

3.6 Administering Databases


In this section we will discuss how to create and handle database
in MongoDB using
various commands.
(1) Create Database
Open the command prompt and type the command mongosh for starting the
mongobB
shell. T he test> prompt will appear. For creating a database we need to use the "use"
command.
Syntax
use Database name
For example

mongosh mongodb//127.0.0.

test> use mystudents


switched to db mystudents
nystudents>

TECHNICAL PUBLICATIONs- an
up-thrust for knowedge
Full Stack Web Development 3- 21 MONGO DB

To check the currently selected database. use the command


db
mongosh mongodb://127 0 0. %

mystudents> db
mystudents
mystudents>

(2) Displaying allthe databases present in the system


We can see the list of databases present-in the MongoDB using the command show dbs
-
For example

A mongosh mongodb://127.0.0.

mystudents> sho# dbs


admin 180.00 Kiß
config 72.00 Ki8
local 72.00 Kil
aystudents>

Note that in above listing we can not see the mystudents database. This is because we have
not inserted any document into it. To get the name of the database in the listing by means of
show command, there should be some record present in the database.
(3) DropDatabase
is used to delete the database. For -
The dropDatabase() command example

mongosh mongodb/n27.0.0. X

mystudents> db.dropDatabase ()
{ ok:
, dropped: 'nystudents' }

nystudents>

TECHNICAL PUBLICATIONS
-
an up-thrust for knowledge
Full Stack Web Development 3-22 MONGO DB

Review Question
1. Write the MongoDB command to create and drop the database.

3.7 Managing Collections


After creating some sample database we must create some collection inside that database
We can perform various operations such as insert, delete and update on this collection. These
operations are called CRUD operations. CRUD stands for Create, Read, Update and Delcte
operations.
1) Create Collection
Wecan create collection explicitly using createCollection command.

Syntax
db.createCollection(name,options)
where
name is the name of collection
options is an optional field. This field is used to specify some parameters such as size,
maximum number of documents and so on.
Following is a list of such options.
Field Type Description
capped Boolean Capped collection is a fixed size collection. It automatically
overwrites the oldest entries when it reaches to maximum size. If it
is set to true, enabled a capped collection. When you specify this
value as true, you need to specify the size parameter.
autolndexID Boolean This field is required to create index id automatically. Its default
value is false.
SIZe Number This value indicates the maximum size in bytes for a
clapped
collection.
Max Number Itspecifies the maximum number of documents allowed in capped
collection.
For example - Following command shows how to create collection in a database using
explicit command

mongosh mongodtin27.00.

test> use myStudent's


switched to db yStudents
nyStudents> db.createCollection(Student details")

nyStudents>

TECHNICAL PUBLICATIONS- an up-thrust


for knowledge
Full Stack Web Development MONGO DB
3-23
2) Display Collection
To check the created collection use the command "show collections" at the command
prompt

mongosh mongodb://127.0.0. %
+

myStudents> show collections


Student_details
myStudents>

3) Drop Collection
The drop collection command is actually used to remove the collection completely from
the database. The drop command removes a collection completely from database.

Syntax
db.collection name.drop)

For example

mongosh mongodb://127.0.0. X

myStudents> db.Student_details.drop();
true
myStudents>.

database
of the collection by using "show collections"
in the
We can verify the deletion

TECHNICAL PUBLICATIONS- an up-thrust for


knowledge
Full Stack Web Development MONGO DB
3-24

mongosh mongodb//127.0.0. x

myStudents> show collections


myStudents>

4) Insert documents within the collection


The document is inserted within the collection. The document is analogous to rows in
database.
Syntax
name.insert key,value
db.collection
For example

mongosh mongodb:/27.D.0.

nyStudents> show collections


nyStudents> db.createCollection("Student details")
myStudents> db.Student_details.insert("nane":"AAA", "age:22})
acknowledged: TuE,
insertedTds: 1'0': DbjectId("643e4b63436497399ala2a66") }

myStudents>

We can verify this insertion by issuing following command

TECHNICAL PUBLICATIONS- an up-thrust for knowiedge


Full Stack Web Development 3- 25
MONGO DB

mongosh mongodt://127 0.0

myStudents> db.Student_details. find()


Iid: ObjectId("643elb63u36497399ala2a66" ), name: *AAA', age: 2
j J

myStudents>

5) Inserting Multiple Documents


It is possible to insert multiple documents at a time using a single command. Following
screenshot shows how to insert multiple documents in the existing collection.

Emongosh mongodb//12700.X

ayStudents> var allStudents =

"nane":"BB8",
"age":

"nane" "DDD",
"age":1

;
nyStudents> db.Student_details. insert (allStudents)

acknowledged tet :

insertedIds:
0bjctId("643e513d436497399ala2a67")
*0': 8d436497399ala2a68")
"1': 0bjectId("643e51

nyStudents>

To verify the existence of these documents in the collection you can use find command as
follows -

mongosh mongodb://127.0.0.

myStudents> db.Student_details.find()
ObjectId("643e4b63436497399ala2a66") name: 'AAA age: 22 },
,

{
-id: 0biectId("643e518d436497399ala2a67 "), name: '888 age: 29 }.
{-id: ObiectId("643e518d436497399ala2a68 "), name: 'DDD', age: }
{_id: 2i
myStudents>

6) Delete Documents
For deleting the document the remove command is used. This is the simplest command.

TECHNICAL PUBLICATIONS- an up-thrust for knowedge


3-26 MONGO
Full Stack Web Development DE

Syntax name.remove(delete criteria)


db.collection

For example
can find out the documents
present in the collection using find() command
First of all we

mongodb:tn27.00.
mongosh
db.Student_details.find()
nyStudents>0bjectIJ("643eUb63436497399ala2a66"),
0bjectId("643e518d436u97399ala2a67" nàme: AAA', age: 22 }
name : 'BBB age: 20
id: ), }.

{_id: DbiectIJ("643e 518d4364g7399ala2a68"), name: DDD', age: 21


1

{ id:
nyStudents>
-
as follows
a record with name "DDD" we can issue the command
Now to delete
X
mongosh mongodb:N270.0.
db.Student_details.deleteOne({"name":"DDD"})::
yStudents> deletedCount: }

I acknowledged: tue,
yStudents>

we can verify if the desired data is deleted or not.


Now using find) command

mongosh mongodb:/27.0.0.
x

()

find
.

ByStudents> db.Student _details


0bjectId("643e4b63436497399ala2 a66"), name: 'AAA age: 22},
{

id: name: "BBB, age: 20}


1

id: Dbjectld ("643e518d436497399ala2a67 "),

yStudents>

7) Delete All Documents For


-
example
For deleting all the documents from the Collection, we use.deleteMany).

mangosh mongodo//12790

ayStudents> db.Student _details.deleteMany({})


,
1 acknosledged: deletedCount: 2 } recors
nyStudents>

verifythatthe
Wecan verifyit using db.Student_details.find) command, we can
are deleted or not.

TECHNICAL PUBLICATIONSB- an
up-thrust for knowledge
Full Stack Web Development
3-27 MONGO DB

mongosh mongodb//127.0.0

myStudents> db.Student_details.Find)
myStudents>

8) Update Documents
For updating the document we have to provide some criteria based on which the
document
can be updated.

Syntax
db.collection name.update(oriteria,update data)
For example - Suppose the collection "Student details" contan following documents

mongosh mongodb:l/127.0.0.
.

nyStudents> db.Student_details find()


{
id: 0bjectId (" 643e72de436497399a1la2 a69")) name : AAA', age:
{ ObjectId("643e73b2436497399ala2a6a"),, name:
id: name:
B88 age:
,
{id: 0bjectId("643e73b2u36497399ala2a6b") CCC, age:
{ name: age: 28}
id: ObjectId("643e73b2436497399ala2a6c"), DDD',
myStudents>

And we want to change the name CCC" to "Www", then the command can be issued
as

mongosh mongodtb://27.0.0.
myStudents> db.Student_details. update({"nane*:"CCC*},sen"nane ")
DeprecationWarning: Collection. update() is deprecated. Use updateOne, updateany, or
bulkWrite.
acknowledged: true,
insertedId: nulL,
matçhedCount:
nodifiedCount
,
upsertedCount :

It can be verified using db.Student details.find) command

mongosh mongodb://127.0.0.

nyStudents> db.Student _details. find()


ObjectId("643e72de436497399ala2a69"), nane: AAA age
{-id: 0bjectId("643e73b2436497399ala2a6a"), nane:
{_id: 0bjectId("643e73b2436497399ala2a6b"), name: www age:
{_id: 0bjectId("643e73b2436497399alala6c"), name: DOD', age
1id:
myStudents>

Thus the document gets updated.

TECHNCAL PUBLICATIONS- an up-thnust for


knowedae
Full Stack Web Development MONGO DB
3-28
By default the update command updates a single document. Bt we can update miltiple
documents as well. For that purpose we have to add {multi:trie}
For example
db.Student detals.update({"age":21), $set:("age"23}}(multitrue})
9)Sorting
We can use the sort) method for aranging the documents in ascending or descending
order based on particular field of document.
Syntax
For displaying the documents in ascending order we should pass value 1

db.collection name.find().sort({field name:1))


If we pass -1then the document will be displayed in the descending order of the field.
For example
Suppose the collection contains following documents.

nongosh mongodb:NZT0.0. X

nyStudents> db.Student_details. find()


{ id; ObjectId("643e72deu36497399ala2a69"), name: AAA" age: 22 3
I ObjectId("643e7362436497399ala2a62"), name: BBB age: 2 },
id:
I id: ObjectId 643e73b243649T399a1a2a6b"), name:www age:
I ObjectId("643e73b2436497399ala2a6c"), name: DDD age: 28
id:
myStudents>

For sorting the documents in descending order sort command is used.

mongosth mongodbt127.00. X

myStudents> db.Student_details.find().sort({"age":-)
id: 0biectId("643e73b2436497399ala2a6c"), nane: 'DDD', age: 28 },
id: ObiectId("643e72de436497399ala2a69"), nane: 'AAA', age: 22 },
id: ObjectId("643e73b2436497399ala2a6b"),name: age: 21
id: ObjectId("643e73b2436497399ala2a6a"), name: 'BBB I
age: 29
nyStudents>

If we want to display data in ascending order we issue following command


myStudent> db.Student details.find),sort{'age':1})

Review Question
1.. Explain with suitable examples, CRUD operations in MongoDB.

TECHNICAL PUBLICATIONS-
an up-thrust for
knowledge
Full Stack Web Development MONGO DB
3-29

3.8 Connecting to MongoDB from Node.js


For connecting the Node.js with MongoDB we use MongoClient
Following are the steps used to connect Node.js with MongoDB
Step 1: Install MongoDB driver for Node.js by isuing following commandon the command
prompt
npm install mongodb
Step 2: In the Node.js application program require the MongoDB module by adding following
line of code
const MongoClient= require(mongodb). MongoClient;
Step 3: Define MongoDB Connection URL
const url= "mongodb://127.0.0.1:27017/myStudents";
-
Step 4: Create the instance of MongoClient by passing the above URL toit. It
isas follows
const client = new MongoClient(url);
Step 5:Finally use the connect method to get connected with the database
client.conneçt()
-
The complete code is as follows
App.js
//get the mongoDB client
const MongoClient = require(mongodb').MongoClient;
//Specify the URL of the database to which the connection is to be done
Const url = 'mongodb://127.0.0.1:27017/myStudents;
//Create client instance
const client = new MongoClient(url);
//Connect to the database
function getData()

client.connect()
then(()=>console.log("Connected to Database Successfully!!!"))
.catch(error=> console.log(Failed to Connect',error)

getData();
Output

PROSLENS CUTRUT DEUSCONSOLE TERMINAL

PS E:ybdesExarples\StudertoeEXample> node pp.js a


future version, To use the nax Geryen D

Maming: (urrent Server Discovery and Monitoring ergire is deprecated, reved in


DRINER]
and xill be
(rode:18796) (aKCO8
1scOer and Ponitoring engine, pass option { uselhifiedTopology:
) to the
tre rgoclient constructor.
.. to shay nhere the aming nas created)
(Use node -trace-narnirgs
Cornected to batabase Successfully!!!

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


MONGO DB
Full Stack Web Development 3-30

Program Explanation : In above code,


1) First of all, we have to import the module
'mongodb' using requirc. Thus we are
creating MongoDB client.
means of hostname(localhost) and pou
2) Then specify the URL for MongoDB by
a we arc goinp
number on which MongoDB is running (27017). This is path which
at

to create a database.
a
we are using connect method by passing the above URL. Inside this function
5) Then
name "myStudents".
database object is created by a database
nccessary to install the mongodb
Note that before execution of the above code, it is
package using the following command at the current working directory.
Prompt:>npm install mongodb

Review Question
1. What are the steps to connect Node,js with MongoDB?

3.9 Understanding the Objects Used in MongoDB Node.js Driver


The MongoDBClient
The MongoDBClient object provides interactions to connect to the database. Following
are some commonly used method of MongoDBClient object
Method Purpose
connect(url,options) This method is used to connect to the MongoDB using the specified url.

close(force, callback) This method closes the db and underlying connections.

db(dbname, options) It creates a new DB instance sharing the current socket connections.

isConnected(options) Itchecks if MongoClient is connected.


The db object
The db object is created for conmecting to the database in MongoDB. Following are some
-
commonly used methods of db object
Method Purpose
addUser(username, password, callback) | It adds user to the database.

admin() This method returns Admin db instance.

collection(name, options, callback) Fetch a specific collection. The name is a


collection
name we wish to access. The
callback function accepts
error and names parameters where names an array
is
ofcollection names.

TECHNICAL PUBLICATIONS°-
an up-thrust forknowledge
Full Slack Web Development MONGO DB
3-31
Collections(options,callbacks) This method fetches all thecollections for current db.

crcateCollcction(namc, This method is used to create a new collection on a


options,callback) server with the specified options.

dropCollection(name, options, callback) It drops the collection from the database, removing it

permanently.
listCollcctions( filter, options) This method is used to get the list of all the collection
information for the specified db.

Review Questions
1. Explan the MongoDBClient object and the methods associated with it.
2. Explain the db object and the methods associated with it.

3.10 Simple Applications


In this section we will discuss basic CRUD operations on MongoDB. CRUD stands for
Create, Read, Update and Delete. The CRUD operations are performed in collaboration with
Node.js and MongoDB.
Prerequisite : For performing these operations we need to have MongoDB installed in our
machine. One must also install MongoDB Compass (It is a graphical tool) to verify the
operations performed by node.js on MongoDB.
-
Example Code : In this example, we willcreate a Student database with two fields name
and city.
1) Creation of collection
Step 1: We will create a database studentDB. For that purpose make a folder in your current
working directory. I have created the folder by a name StudentDBDemo.

Step 2 Open the command prompt go to the path of StudentDBDemo. And issue the
commands
D:\NodeJSExamples\StudentDBDemo>npm init
gets created.
And press enter key to accept the default values. By this package.json file
Step Then install the mongodb module using following command
3:
D:
NodeJSExamples\StudentDBDemo>npm install mongodb

a database and collection. The code is as


Step 4 : Now create a node.js file for creating
follows -
create.js require('mongodb').MongoClient;
const Mongo Client =

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


MONGO DB
Full Stack Web Development 3-32
const url="mongodb://127.0.0.1:27017";
const client = new MongoClient(url);
//Connect tothe dabase
const database = "studentsDB";
async function getData()
to
Use createCollection method
let result = await client.connect(): create a collection named
let dbo = result.db(database); Student Info
dbo.create Collection("Student Info"):
console.log("Collection Created!!");
}

getData();
Output

PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL

PS E: \NodeJSExamples\StudentDBDemo> node create.js


Collection Created!!!

:
Program Explanation In above code,
1) First of all, we have to import the module 'mongodb' using require. Thus we are
creating MongoDB client.
2) Then specify the URL for MongoDB by means of hostname (localhost or 127.0.0.1)
and port number on which MongoDB is running (27017). This is a path at which we
are going to create a database.

3) Then we are using connect method by passing the above URL. Inside this function a

database object is created by a database name "studentsDB"


4) Then using the method createCollection for database object we can create a
collection inside the database "studentsDB". Note that here the collection name 1s
"Student Info".
5) The message "Collection Created!!!" is displayed on the console using
console.log
method.

2) Insertion of document
Once the collection is created, we can insert some
document into it. Following 1s all
example code which shows how to insert one document into a collection named Student Into
const Mongo Client require(mongodb').MongoClient;

TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
Full Stack Web Development MONGO DB
3-33
const url = "mongodb://127.0.0.1:27017";
const client = new MongoClient(url);
/ Connect to the database
const database = "studentsDB":
async function getData()

let result await client.connect();


let dbo = result.db(database):
var mydata = {name:"Ankita', city:'Pune":
dbo.collection("Student Info").insertOne(mydata);
console.log("Data Inserted!!!"):

getData():
Output

PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL

PS E:\NodeJSExamples\studentDBDemo> node insert.js


Data Inserted!!!

:
Program explanation In above code,

1) First of all, we have to import the module 'mongodb' using require. Thus we are
creating MongoDB client.
2) Then specify the URL for MongoDB by means of hostname(localhost) and port
number on which MongoDB is running(27017). This is a path at which our database
exists.
a
3) Then we are using connect method by passing the above URL. Inside this function
database object is created by a database name "studentDB". Thus now we can access
to student DB

4) Then a JSON object is in the form (name:value}. We insert data in the collection in
the form of document. This document is created in the form of JSON. Hence the
mydata object is created with some values.
5) This mydata is inserted into the collection using insertOne method using following

code
dbo.collection("Student Info").insertOne(mydata)
can insert many documents in the collection.
In the same manner we

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


MONGO DB
Full Stack Web Development 3-34

Inserting Multiple documents in the Collection


Const MongoClient = require(mongodb).MongoClienit;
const ur="mongodb://127.0.0.1:27017;
const client = new MongoClient(url);
/Connect tothe dabase
const database = "studentsDB";
async finction getData()

let result = await client.connect():


let dbo = result.db(database):
var mydata = |
{name: "BBB", city: "Mumbai}.
{
name: "CCC, cíty: "Chennai" },
{
name: DDD, city: "TDelhi.
{name: EEE,city: "Ahmedabad
}

1:

dbo.collection(Student Info").insertMany(mydata):
console.log(Multiple documents Inserted!"):

getData(0:
Output

PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL

PS E:\NOdejSExamples\StudentDBDemo> node insertMany.js


Multiple documents Inserted! !!

:
Program explanation In above code
We have created array of values in JSON object as Follows
yar mydata = 1

{ name: "BBE, city: "Mumbai },


name: "CCC, city: "Chennai ),

f nane: DDD",city. "Delhi }.


name: EEE, city: "Amedabad' }

Then using the insertMany command we can insert all


the above documents at a time
This program execution can be verified in MongolDB compasS.

TECHNICAL PUBLCATIONSB
an up-thrust for knowledge
Fut Stack Web Development MONGO DB
3-35
Open MongoDB Compass. just connect with mongodb:/localhost:27017, select the
StudentDB database and then select Student Info collection. The following sereenshot
displays multiple documents inserted into it.

studentsDB.Student_Info 5
DCCUME

Documents Aggregations Schamg Explcin Plen Indezes Validaticon

Filter Type a query: (

Field: vlun
5

Find Mo

S
ADD DATA C EXPORT COLLECT1ON I-5 of

„id: 0bjectId('G43d162b6265F487895e799*i
name "Anki ta"
city: "Pune"

)
1d: Object Id('6449dfd84be9f6c8e5eabsbe'
name: "BBB Multiple
c1ty: "Mumbai"
documents are
inserted in the
_id: 0bjectId(' 6449dfd84be9f6coeSeab6bf) database.
name: "CCC"
city: "Chennai"

_id: 0bjectId('6440dfd84be9f6cte5eab6ce')
name: "DDDn
city: "De Lhi

id: Obiect Id('6440dfd84hegf6c9e5eab6c!')

3) Displaying(Read) the data from Collection


We can read all the documents of the collection using find method. Following is a simple
Node.js code that shows how to read the contents of the database.

Display.js
const MongoClient = require(mongodb').MongoClient;
const url = "mongodb://127.0.0.1:27017";
const client = new MongoClient(rl):
I/Connect to the dabase
Const database= "studentsDB";
async function getData()

TECHNICAL PUBLICATIONS- an up-thrust for knowedge


MONGO DB
Full Stack Web Development
3-36

let result = avwait, client.connect():


let db = result.db(database);
db.collection("Student Info"):
let collection =
collection.find({} ).toArray():
let response = await
console.log(response);

getData();
Output
TERMINAL
DEBUG CONSOLE
PROBLEMS OUTPUT

E:\NodeJSExamples\StudentDBDemo> display.js
node
PS

objectId("643fd162b6265f487395e709");
new
id:
name:Ankita
objectd("6440dfdg4begf6coe5eab6be),
new
id:
name: BBB
Mumbai'
city:

new objectId("6440dfdaabe9f6cee5eab6bf"),
id:
name: 'CCC,
city:Chennai"

new
id: objectd("6449dfd84begf6coe5eab6co")
name: DDD

city: Delhi'

id: new ObjectId("6440dfd&abegf6cee5eab6c1"),


name: EEE

city: Ahmedatbad

: In
Program explanation above code.
we
4) First of all. have to import the module 'mongodb' using we are
require. Thus
creating MongoDB client.
5) Then specify the URL for MongoDB by means port
of hostname(localhost) and
number on which MongoDB database
is running(27017). This
is a path at which our
exists.

TECHNICAL
PUBLICATIONS-
an up-thrust
for knowledge
Full Stack Web Development 3-37 MONGO DB

6) Then we are using connect method by passing the above URL. Inside this function a
database object is created by a database name "studentDB". Thus now we can access
to studentDB.

7) Then for reading the contents present in the documents of the collection we use the
find) method.
8) We use toArray method associated with the find) because it returns an array that
contains all documents returned by the cursor.
4) Update document
We can modify the document using updateOne method. Following code illustrates it -

Update.js
const MongoClient = require('mongodb).MongoClient;
const url="mongodb://127.0.0.1:27017";:
Const client new MongoClient(url);
/Connect to the dabase
const database = "studentsDB";
async function getData()

let result = await client.connect();


let dbo = result.db(database);
var mydata = { name: "DDD"};
var newdata = {$set: {name:"TTT", city:"Jaypur"}}
dbo.collection("Student Info").updateOne(mydata,newdata):
console.log("One Document Updated!!");

getData();
Output

PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL

PS
E:\NodeJSExamples\StudentDBDemo> node update.js
One Document Updated!!!

We can verify the above updation


Compass. Just open the database
in MongoDB
see the modification.
StudentDBusing MongoDB Compass to

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development MONGO DB
3-38
Explain Plon Inderes Volidd
Documents Aggregations Scheme

Filter Find
query: field: 'value' Reset
]
4

Type a

of 5
ADD DATA
C EXPORT COLLECTION 1-5

id: ObjectId(" 644pdfdsabe9 FEcee5eab6be')


name "BBB"
city: "Mumbai"

id: 0bjectid (' 6440d FdB4be9 f6cee5eab5bf')


name: CcC

city: "Chennai"

_id: object Id(' 64a9dfds4be9 f6cee Seab6ce')


name:TTT"
city: 3aypur
This record is
updated
id: ObjectId('6449dfd8tbe9 f6cee Seab6c1')
name: "EEE
city: "Ahmedabad

:
Program explanation In above code,
We are updating one document using updateOne method. This method require two
parameter first one is the existing data and second one is the new data which you want to put
in place of the existing one. This can be done with the help of following lines of code
var mydata = {name: "DDD}; Jlezisting record with name "DDD"
var newdate = {Sset: {namne:1T city:"Jaypur} //replace it by a new data
Then updateOne method is called by passing these two parameters.
5) Delete document
This is the operation in which we are simply deleting the desired document. Here to delete
a single record we have used deleteOne method. The
code is as follows -
deleteDne.js
const MongoClient require(mongodb'), MongoClient;
const urd ="mongodb://127.0.0.1:27017";
const client = new MongoClient(url);
11Connect to the dabase
const database = "studentsDB;
async function getData(0

TECHNICAL PUBLICATIONSan
up-thrust tor knowiedge
Full Stack Web Development 3-39 MONGO DB

let result = await client.connect):


let dbo = result.db(database):
var mydata = { name: "TTT":
J/Delete the document

dbo.collection("Student Info").deleteOne(mydata):
console.log('One Document Deleted!!"):

getData():
Output

PROBLEMS OUTPUT D6UG CONSOLE TERMINAL

PS E:\NodeJSExamples\StudentDBDemo> node deletene.js


One Document Deleted! !!

We can verify it using MongoDB Compass. Note that the name TTT is missing.

JADD DATA C EXPORT COLLECTION 1-4 of 4

_id: ObjectId ('643fdl62b62 65 f487995e709)


name: "Ankita"
city: "Pune"

id: 0bjectId('6440dfd84be9f6c@eseab6be')
name: "BB8"
city: "Humbai"

id: 0bjectId( '6-449d fd84be9f6cêeseab6bf)


name: "CcC"
city: "Chennai"

0bjectId('644@dfds4be9r6cêe5eabác1)
id:
name: "EEE
city: "Ahnedabad"

The above deletion operation can be veritied by displaying the contents of the collection

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development MONGO DB
3- 40

PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL

PS E:\NodeJSExamples\studentDBDemo> node display• js

new ObjectId
id: 643fd62b6265F487895e709")»
name:Ankita
city:Pune'

new
id:
name: BBB
objectd("6440dfds4begf6coe5eab6be") Note that the
document
city: Mumibai
containing the
name field
new objectId("6440dfd8abe9f6cbeSeab6bf"), with value
id: "TTT" is not
name:COC
city: Chennai present.

new objectid("6A40dfd84be9f6coeSeab5c1"),
id:
name: EEE,
city: 'Ahmedabad'

6) Sorting documents
Data can be arranged in sorted order in the collection. For displaying the sorted ordered
data we use the method sort. Following code illustrates how to display the data in ascending
order of the filed named city.
Sort.js
const MongoClient = require('mongodb).MongoClient;
const url="mongodb://127.0.0.1:27017";
const client = new MongoCient(url);
// Connect to the dabase
const database = "studentsDB";
async function getData()
{

let result = await client.connect):


let db = result.db(database);
let collection = db.collection('Student Info");
var mydata = (city:1};
let response = await collection.find().sort(mnydata).toArrav():
console.log(response);

getData();

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
Full Stack Web Development
3- 41 MONGO DB

Output

PROBLEMS OUTPUT DEBUG CONSOLE


TERMINAL
PS E:\NOdeiSExamples\StuderntDBDemo>
node sort.js
new ObjectId("6449dfd84be9f6ceSeab6c1"),
idi
name'EEE
city: 'Ahmedabad

new Objectd("6440dfd8Abegf6cleseab6bf"),
id:
name: 'CCC
city: 'chennai

ids new Objectd("6440dfd3Abegf6ceeseab6be"),


name: BBB'
city: Mumbai'

new
id: objectd("643fd162b6265f487395e709"),
name: Ankita",
city: Pune

Program explanation : Inabove code to sort in ascending order we use sort. The key field
based on which the document is to be sorted is city. We have passed 1 along with it for
displaying the city names in ascending order. If we pass -I then the cities are displayed in
descending order. Simply change the above code as
var mydata = { city: -1};

Review Questions
1. Explain insertion and deletion database operation using NodeJs.
2. Write aprogram to display the sorted data in the database using NodeJs.
3. What is CRD ? Eyplain the CRUD operations in node,js.
3.11 Advanced MongoDB
Following are the features of advanced MongoDB.

3.11.1 Indexing
For efficient execution of queries the indexing is used. If' we use the query without indexes
then the execution of that query will be very slow.
Definition of indexIndex is a special data structure that store small part
:
of collection's
data in such a way that we can use it in queryng.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


FullStack Web Development MONGO DB
3-42
or collection and keep track of
The index store the values of index fields outside the table
their location in the disk.
:
Demonstration
collection
In order to create an index, we will use the database named nystudents. The
Student_details will be used for creating index.
Command Prompt- mongo
> use ystudents
switched to db eystudents
.
b db.Student_details find () :
: ObjectId("6@545eSc5783af5ledeb3775"), "AAA", "age 22 }
"_id" "name" : )
"BBB", "age" 21
"_id" : ObjectId("60545e695783af5ledeb3776"), "name"
id. "CCC", "age 23 }
Objectid ("60545e735783ef5ledeb3777" ), "name"
id.
id
: 0biectId("60545e7d5783af5ledeb3778"),
bjectld("60545fe35783afSledeb3779" ),
"name"
"name"
"DOD, "age" : 20)
"EEE", "age" 21 )
:bjectid("60545f125783af5ledeb377a"), "name "FFF", "age" 24 }
: :
"GGG", "age" : 22 }
id 0bjectId ("6es45f1a5783af5ledeb3776"), neme"

1) Index creation
Syntax for creating index is
db.<collection>.createlndex({KEY:1})
The key determines the field on the basis of which the index is created. After the colon the
direction of the key( 1l or -1) is used to indicate ascending or descending order.
The MongoDB will generate index names by concatenating the indexed keys with the
direction of each key with underscore as separator. For example if the index is on the field
name and the order as 1 then the index will be created as name 1.
We can also use name option to defne custom index name while creating the index.
-
For example
> db.Student details.createlndex({nane:1}, {name:'Student's Names"} )
-
The result will be as follows

o Coranc Prompt mongo

db.5tudent_details.createlndext (name:1), {name:"Student's tianes") )

"reatedlollectionAutonatically" false,
"numIndexesbefore"
:

2,
"re IndexesAfter"
:

3.
1
"ok;

Thus index gets created on the collection Student details.

TECHNICAL PUBLICATIONSan
up-thrust for knowiedge
Full Stack Web Development MONGO DB
3- 43
2) Find index
We can find all the available indexes in the MongoDB by using getindexes method.
Syntax
db.<collection>.getIndexes()
-
For example
>db.Student_details.getindexes()
The result will be
GComnmand Prompt- mongo
db.Student_details.getIndexes()

"v": 2,
:
"key" :
" id" 1

:
"name" "id_"

"v": 2,
"key" : {

"name" : 1

:
"name" "Student's Names"

Note that the output contains the defaultid index and user created index.

3) Drop index
To delete an index we use droplndex method.
Syntax
db.<colection>.droplndex(Index Name)
For examnple
db.Student details.droplndex("Student'sNames")

The result will be


-
Command Prompt mongo
db.Student details.dropIndex ("Student's Names")
)
H"nIndexesWas" 2, "ok" :1

4) Compound index
We can create index on multiple fields in MongoDB document. For
example

db.Student details.createlndex( {name:1, age:-1})


TECHNICAL PUBLICATIONS- an up-thrust for knowedge
Full Stack Web Development MONGO DB
3-44

It will sort by name in ascending order and age in descending order. If the names are same
then the descending order of age can be noticed.

3.11.2 Aggregation
Aggregation is an operation used to process the data that results the computed results. The
aggregation groups the data from multiple documents and operate on grouped data to gct the
combined result. The MongoDB aggregation is cquivalent to count(*) and with group by in
sql. MongoDB supports the concept of aggregation framework. The typical pipcline of
-
aggregation framework is as follows
Input Output
Smatch Sgroup $sort

Fig. 3.11.1 Aggregation framework

1) Smatch) stage - Filters those documents we need to work with, those that fit our
needs.
2) Sgroup) stage - Does the aggregation job.
3) Ssort() stage - Sorts the resulting documents the way we require (ascending or
descending).
The input of the pipeline can be one or several collections. The pipeline then performs
successive transformations on the data and the result is obtained.
Syntax for aggregate operation
db.colection name.aggregate(aggregate operation)

Demo example
For demonstration purpose, I have created a database named CustomerDB inside which
there is a collection document named customers. Some data is already inserted into it. The
contents of customers document are as shown below -
-
Command Prompt mongo X
> use CustonerDB
Sitched to db CustomerDB
db.customers.find()
i. CbiectId("610e57c112Be95223b716fcf"), "name": "AAA", "type":"Develoner" )
: objectId("610e57ff128e95223b716fde" ), "name" : "BBg".
id
"type" : "Tester" }
id" : objectd("610e5834128e95223b716fd1"), ,
"name"
ObjectId("610e585c128Be95223b716fd2") "nane"
"CCC", "type" : "Tester" }
k"id": : ObiectId("610e587d128e95223b71ófd3"), "DDD", "type": "Developer"
}
I34 "name" :"EEE", "type" : "Developer )

TECHNICAL PUBLICATIONS-an
up-thrust for knowledge
Full Stack Web Development
3- 45 MONGO DB

Now issue the following command


> db.customers.aggregate(í{$group:{ id: "Stype', category: ($sum :
1}})
-
The result will be

G Command Prompt nongo


> db.customers. aggregate ([ ($group : (_id: "stype", category: ($sum :
" 1}}}1)
id": "Developer", "category": : 3 )
" id" : "Tester",
"category" 2 )

-
The above command willdisplay total categories of the customers In our database there
are two types of customers -"Developer" and Tester". There are 3 developers and 2 testers in
the collection document. The aggregate function is applied on the Sgroup.
Similarly if we want to find only Developers from the collection document customers then
we use Smatch for aggregate function. The demonstration is as follows -
- mongo
Ci Command Prompt
db.customers. aggregate([{Smatch : (type:"Developer"}}1)
: :
"_id" ObjectId("610e57c1128e95223b716fcf"), "name "AAA"
","type "Deve loper" }
"_id" : 0bjectId("610e585c128e95223b716fd2"), *name" "DDD", "type" "Developer" }
:
"_id" ObjectId ("610e587d128e95223b716fd3"), "name" "EEE", "type "Developer" }

Expressions used by aggregate function


Expression Deseription
$sum Summates the defined values from all the documents in a collection

Savg Calculates the average values from all the documents in a collection

Smin Return the minimum of all values of documents in a collection

$max Return the maximum of all values of documents in a collection

SaddToSet Inserts values to an array but no duplicates in the resulting document

Spush Inserts values to an array in the resulting document

$first Returns the tirst docunent from the source document

$last Returns the last document trom the source document

TECHNICAL PUBLICATIONs- an up-thrust for knowledge


Full Stack Web Development 3-46 MONGO DB

3.11.3 Map Reduce


Map reduce is a data processing programming model that helps in performing operations
on large data sets and produce aggregate results.
Map reduce is used for large volume of data. The syntax for map reducc is
>db.collection.mapReduce(
-
function() femit(key, value):}, map function
function(key,values) {return reduceFunction), reduce function
out: collection, the collection is created in which the result of mapReduce can be stored
query: document,
sort: document,
limit: number

Where
1) map Function : It uses emit() function in which it takes two parameters key and value
key. Here the key is on which we make groups(such as group by name, or age) and the
second parameter is on which aggregation is performed like avg0, sum) is.calculated
on.
2) reduce Function: This is a function in which we perform aggregate functions like
avg), sum)
3) out : It will specify the collection name where the result will be stored.
4) query We will pass the query to filter the resultset.
:

5) sort: It specifies the optional sort criteria.


6) limit : It specifies the optional maximum number of documents to be returned.

Demo Example :
Step 1 : Create a collection inside the database mystudents. The collection is created using
name Student info.

Cs Command Prompt mongo


-
X

|>use mystudents
switched to db mystudents
db.createCollection("Student_info")
i : 1 }
"ok"

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


Full Stack Web Development MONGO DB
3- 47

Step 2 : Now we will insert documents inside the collection Student info using following
command
db.Student info.insertMany( [
{name:"Ankita", marks:96}.
{name:'Ankita", marks:86).,
{name:"Ankita", marks:92},
{name:"Kavita", marks:87).
{name:"'Kavita", marks:74},
{name:"Kavita", marks:86 }

1)
Now in order to display the contents of the collection we issue the find) command.
Command Prompt - mongo X

db.Student_info.find() .pretty() 4 -Issue this command to display the documents in the collection
"_id" : ObjectId("6110ce2 a85089e2d2c7fac22"),
"name": "Ankita",
"marks": 96

" id" : ObjectId("6110ce2a85089e2d2c7fac23"),


"name" :
"Ankita",
"marks": 86

" id" : ObjectId("6110ce2a85eg9e2d2c7fac24"),

"name": "Ankita",
"marks" . 92
" id" : objectId ("6110ce2a85es9e242c7fac25"),
"name :
"Kavita",
: 87
"marks"

"id" : objectId ( "6110ce2a85889e2d2c7fac26"),


:
"name "Kavita",
74
"marks":

"_id"
:

ObjectId("611ece2a85089e2d2 c7fac27"),
:
"name" "Kavita",
"marks" : 86

Step 3: Now we will apply mapReduce function

EC Command Prompt
- mongo Create a 'map' function
which stored name and
>
var map = function() { emit(this.name, this.marks);};: D
marks fields
> var reduce = function (name, marks) {return Array.sum(marks);}:.
>
db.Student_info.mapReduce( Create a 'reduce'
map, -Pass both the 'map' function that
reduce,
(out:"Result"}
and 'reduce' finds the sum of
.. ): functions to
mapReduce and
allthe marks of
: 1 } each student
{"result" "Result", "ok"
:

create a collection
named "Result".

TECHNICAL PUBLICA TIONs- an up-thrust for knowedae


Full Stack Web Development MONGO DB
3- 48
It is
Step 4 : The output of the mapReduce can be seen with help of find) command.
illustrated by following screenshot -

C Command Prompt - mongo


db.Result.find ().pretty()
"
id": "Ankita", "value": 274 }

"_id" : "Kavita", "value" :


247}

Advantages of mapReduce
1) MapReduce allows the developer to store complex result in separate collection.
2) MapReduce provides the tools to create incremental aggregation over large collections.
3) It is flexible.

Review Questions
1. List and explain thefeatures of advanced MongoDB.
2. What is the purpose of mapReduce. Explain it with suitable example.

3.12 Two Marks Questions with Answers


Q.1 What is NoSQL ?
:
Ans. NoSQL stands for not only SQL. It is nontabular database system that store data
differently than relational tables. There are various types of NoSQL databases such as
document, key-value, wide column and graph.
Using NoSQL we can maintain flexible schemas and these schemas can be scaled easily with
large amount of data.
Q.2 Enlist the features of NoSQL.
:
Ans.
1) The NoSQL does not follow any relational model.
2) It is either schema free or have relaxed schema. That means it does not require
specific
definition of schema.
3) Multiple NoSQL databases can be executed in distributed fashion.
4) It can process both unstructured and semi-structured data.
5) The NoSQL have higher scalability.

TECHNCAL PUBLICATIONS-an up-thrust


for knowiedae
Full Stack Web Development MONGO DB
3- 49

Q.3 Enlist the features of MongoDB.

Ans. :

1) It is a
schema-less, document based database system.
2) It provides high performance data persistence.
3) It supports multiple storage engines.
4) It has a rich query language support.
5) MongoDB provides high availability and redundancy with the help of replication.
That means it creates multiple copies of the data and sends these copies to a different server
-sothat if one server fails, then the data is retrieved from another server.
Q.4 How the terms in MongoDB are different from SQL ?
Ans. The terms in SQL are treated differently in MongoDB. In MongoDB the data is not
:

stored in tables, instead of that, the there is a concept called collection which is analogous to the
tables. In the same manner the rows in RDBMS are called documents in MongoDB, likewise
the columns of the record in RDBMS are called fields.
Q.5 Explain the createUser command in MongoDB.
Ans. :
The user accounts are created using the createUser) method.
Stax
db.createUser(user, wIiteConcerm)
Parameters
user: Is a document with authentication and access information about the user to create.
writeConcern: This document represents the level ofwrite concern for creation operation.
Q.6 How remove users from MongoDB ?
For removing the user, the db.dropUser( is used.
:
Ans.

Syntax
db.dropUser(usernsme)
Q.7 Enlist any four data types in MongoDB.
Ans. Following are various types of data types supported by MongoDB.
:
numerical value.
1) Integer: This data type is used for storing the
i.e. true or false.
2) Boolean: This data type is used for implementing the Boolean values
3) Double Double is used for storing floating point data.
:

4) String: This is the most commonly used data type used for storing the
string values.

S) MinMax keys : This data type is used to


compare a value against the lowest or highest

BSON element.
TECHNICAL PUBLICATIONS- an up-thrust for knowledge
Full Stack Web Development 3-50 MONGO DB

For storing an array or list of multiple values in one key, this data type is usecd.
:

6) Arrays

Q.8 Explain how to create collection inMomgoDB ?


Ans. :
After creating some sample database we must create some collection inside that
database.
We can create collection explicitly using createCollection command.

Syntax
db.createCollection(name,options)
where
name is the name of collection
options is an optional field. This field is used to specify some parameters such as size,
maximum number of documents and so on.
Q.9 How to insert multiple documents in a MongoDB database ?
Ans. :
It is possible to insert multiple documents at a time using a single command. Following

command shows how to insert multiple documents in the existing collection.


var = allStudents =

"name": AAA,
"age": 20
}.
{
"name: BBB,
"age": 21

"name": CCC,
"age": 22

1:

>db.Student details.insert(allStudents):
Q.10 Explain the MongoDBClient in detail.
Ans. : The MongoDBClient object provides interactions to connect to the
database. Following
are some commonly used method of MongoDBClient object.
Method Purpose
connect(url,options) This method is used to connect to the MongoDB
using the specified url.
close(force, callback) This method closes the db and underlying
connections.

TECHNICAL PUBLICATIONS-
an up-thrust for knowedge
Full Stack Web Development MONGO DB
3-51
db(dbname, options) It creates a new DB instance sharing the current socket connections.

isConnected(options) It checks if MongoClient is connected.

Q.11 What is Map reduce ?


Ans. : Map reduce is a data processing programming model that helps in performing operations
on large data sets and produce aggregate results.

Map reduce is used for large volume of data. The syntax for map reduce is
>db.collection.mapReduce(
function(0 {emit(key,value):}, <-map function
|function(key,values) {return reduceFunction}, { <-reduce function
Out: collection, <-the collection is created in which the result of mapReduce can be stored
query: document,
sort: document,
limit: number

Where
1) map function : It uses emit) function in which it takes two parameters key and value key.

Here the key is on which we make groups(such as group by name, or age) and the second
parameter is on which aggregation is performed like avg), sum) is calculated on.
2) reduce function :
This is a function in which we perform aggregate functions like avg0,
sum()
3) out : It will specify the collection name where the result will be stored.

4) query : We will pass the query to filter the resultset.


5) sort :It specifies the optional sort criteria.
6) limit :It specifies the optional maximum number of documents to be returned.

TECHNICAL PUBLICATIONS- an up-thrust for knowedge


Full Stack Web Development MONGO DB
3-52

Notes

TECHNICAL PUBLICATIONS-
an up-thrust for
knowledge
UNIT IV

4
Syllabus
Express and Angular

Implementing Express in Node.js - Configuring routes - Using Request and Response objects
Angular - Typescript - Angular Components - Expressions - Duta binding Built-in directives.
-

Contents
4.1 Implementing Express in Node,js
4.2 Configuring Routes
4.3 Using Request and Response Objects
4.4 Introduction to TypeScript
4.5 Type Annotations

4.6 Variables and Constants


4.7 Understanding Interfaces
4.8 Implementing Classes
4.9 Implementing Modules
4.10 Understanding Functions
4.11 Basics of Angular
4.12 Angular CLI
4.13 Creating First Application in Angular
4.14 Angular Architecture
4.15 Angular Components
4.16 Expressions
4.17 Data Binding
4.18 Built-in Directives

4.19 Two Marks Questions with Answers

(4- 1)
Full Stack Web Development Express and Angular
4-2

Part I: Express

4.1 Implementing Express in Node.js


Express is web application framework used in node.js. It has rich set of features that
help in building lexible web and mobile applications.
Features of Express
1) Middleware : Middleware is a part of program, that acccsses to thc database and
respond to client requests.
2) Routing : Express JS provides a routing mechanism so that it is possible to reach to
different web pages using the URLs.
3) Faster server side development : 1 is very convenicnt to develop server side
development using Express JS.
:
4) Debugging Express Js makes debugging casier by providing the debugging
mechanism.

4.11 Installing Express


Express is installed using Node Package Manager(npm). The command issued for
installing the express is,
Prompt:>npm install express
Foliowing is a simpie application program that ues Express JS for displaying "welcome
message" on the web page.
app.js
Var express require(epress),
spp=expess(
Var

app.getT, function(regres){
Greate a Ioute. This is a
res,sendCWelcome Userl!); default route

var server app isten(B082, function()


console log 'ServerStarted');

Output
On the terminal window or on command prompt window issue the command
> node appjs

TECHHICAL PUBLICATIONSan up-thrust for hnpwtodgo


Fuft Stack Web Development 4-1 Express and Angular

Following screenshot illustrates it


-

PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL

PS E:\EXpressExamples> node app.js


Server started!

Open some web browser and issue the URL "localhost: 8082"
(x
localhost8082

O localhost:8082

Welcome User!!

:
Program example In above code,
I) We have imported express.js module using require function. The express module
returns a function and this function returns an object. This object can be used to
configure the Express application. In above code, it is the app object.
-
2) The app is an instance of express module. To the method of this instance The
can be passed. The general
HTTP request, response objects and a callback function
syntax is
app.method(path, handler)

here,
is an HTTP GET, PUT, POST
or DELETE
method
handler is the function executed when the route is matched.

3) Then using the app.listen to function to make our server application listen to client
requests on port number 808.2. We can specify any desired port number.

TECHNICAL PUBLICATIONS- an up-ihnust for knowtedge


Full Stack Web Development Express and Angular
4-4

Creating instance of express


an instance of the express class. This instance acts as the HTTP server for tbe
•Create
Node.js application. Following lines create an instance of express
var express = require('express):
var app = express():

Configuring express settings


The express object provides the set, enable and disable methods to set the values of
application settings.
Similarly, the express object provides get, enabled and disabled methods to get the
values of application settings.
The application settings can be done with the help of following values.
env It defines the environment mode such as "development", "testing" and
"production". The default is the value of process.env.NODE ENV.

trust prOxy Enables or disables the reverse prOxy support.

json spaces It specifies the number of spaces to use when creating the JSON response. The
default value in development is 2 and 0 in production.

json replacer It defines the JSON replacer callback function. Default value is NULL.

strict routing It enables or disables the strict routing.

view engine It specifies the default template engine extension while displaying the web page.

views For specifying the path for template engine it is used. Template engine is a package
that renders the data or values in HTML pages.

4.2 Configuring Routes


Routing is a manner by which an application responds to a client's request based on
particular endpoint. The sample endpoints are,
localhost:8082/aboutus
localhost:8082/contact
localhost:8082/home
There are various types of requests such as GET, POST, PUT or DELETE. While
handling these requests in your express application, the request and response
parameters
are passed. These parameters can
be used along with the send method.
Followingapplication represents how to performing routing expressusing

TECHNICAL PUBLICATIONS®.-an up-thrust


for knowledge
Full Stack Web Development Express and Angular
4-5
app.js
var express = require('express');
var app = express():

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

res.send("Welcome User!!"):
}:
I/routing to 'about us' page
app.get(/about', function(reg.res) {
res.send("This is about us page"):
}):
I/routing to 'contact' page
app.get(/contact', function(reg,res) {
res.send("This is displays contact information");
}):

var server = app.listen(8082, function(){


console.log("Server started!");
}):
Output

X
S localhost:8032/about X +
localhost:8082/about

This is about us page

S localhost:8082/contact X +
O localhost:8082/contact

This is displays contact information

TECHNICAL PUBLICATIONS- an up-thrust for knowtedge


Full Stack Web Development Express and Angular
4-6

4.3 Using Request and Response Objects


which are
The request and response objects are the parameters of the callback function
params, body, headers and
used in Express application. We can get the request query,
cookies.
Request object
The request object represents the HTTP request and contains properties for the request
query string, parameters, body and HTTP headers
For example
app.get(, function(req,res\ }

Request object
The properties and methods of request object are as follows -
Properties /Methods Deseription
req.app This property is used to hold a reference to the instance of the express
application.

req.body It sontains key-value pairs of data submitted in the request body. By


default, it is undefined and is populated when you use body-parsing
middleware such as body-parser.

req.cookies This property contains cookies sent by the request.

req.ip req.ip is remote IP address of the request.


req.path It isthe path part of the request URL.
req.route req.route is currently-matched route.

req.accepts(types) It is used to check content types are acceptable, based on the request's
Accept HTTP header field. For example
req.accepis("html');

req.get(field) This method returns the specified HTTP request header field.

req.is(type) This method returns true if the incoming request's "Content-Type"


HTTP
header field matches the MIME type specified
by the type parameter.

TECHNICAL PUBLICATIONS° - an up-thrust for


knowedge
Full Stack Web Development 4-7 Express and Angular

Example code for demonstrating request object


app.js
var express = require('express');
var app = express():
app.get(, function(req,res) {
console.log("URL: ",req.originalUrl);
console.log("'Protocol: ",req.protocol):
console.log("IP: ",req.ip);
console.log("Path: ",req.path);
console.log("Hostname",req.hostname):
res.send("Welcome User!!"):

var server = app.listen(8082, function(){


console.log("Server started!");

Output

PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL

PS E:\ExpressExamples\RequestDemo> node app-js


Server started!
URL:
Protocol: http
IP: :1
Path:/
Hostname localhost

Program explanation In above program, we have called various methods of Request object
:

such as req.originalUrl, req-protocol, req.ip, req-path, and req.hostname


HTTP response which is sent by an
Response object :The Response object (res) specifies the
-
Express app when it gets an HTTP request. For example
app.get(r, function(req.res)X}

Response object
response object.
• Following are some properties and methods of
Properties / Methods Description
It holds a reference to the instance of the express application that
res.app is using the middleware.

res.headersSent Boolean property that indicates if the app sent HTTP


It is a

headers for the response.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 4 - 8 Express and Angular
response
res.append(ficld [, value]) This method appends the specified value to the HTTP
header field.
res.attachment([filename]) This method facilitates you to send a file as an attachment in the
HTTP response.
res.cookie(name, This method is used to set acookie name to value. The value can
value [, options]) be a string or object converted to JSON.
-
res.end([data] [, encoding]) This method is used to end the response process. For example
res.end()

res.get(field) This method provides HTTP response header specified by ficld.


For example - res.get(*Content-Type')
res.send([body) This method is used to send HTTP response.
res.set(field [, value]) This method is used to set the response of HTTP header field to
value.
res.status(code) This method sets an HTTP status for the response. For example
res.status(400).send('Bad Request');
res.status(200).send(Ok');

Example code for demnonstrating response object


app.js
var express = require('express');
var app = express();
app.get(/, function(req,res) {
Newresponse is
var new_response ='<html><head<title> Response Demo prepared and sent
</title></head><body> <h1>Welcome User</h1><body><html>: Ove respOnse
res.status(200):
object.
res.set({
'Content-Type': text/html',
'Content-Length':new _response.length
):
res.send(new_response);:
console.log(res.headersSent):
}):

var server = app.listen(8082, function(){


console.log("Server started!");
console.log("Sending HTML Contents to the browser.. uy:
):

TECHNICAL PUBLICATIONS- an
up-thrust for knowtedge
Full Stack Web Development 4-9 Express and Angular

Output

Response Demo +
O localhost:8082

Welcome User Note that <html>


body and head(title) is
displayed

Program explanation :
In above program,

We have created an HTML document in a variable new response. This document is sent
to browser using res.send method. Before sending this document to the browser we have set
the status code as 200 (i.e. OK) and the content-type and content length. The status of headers
sent is also displayed on the console window. For performing all these tasks, the
corresponding methods of Response object are used.

Part Il : TypeScript

4.4 Introduction to TypeScript


TypeScript is a typed superset of JavaScript. Any valid JavaScript code is basically a
valid code for typescript as well.
TypeScript extends JavaScript by adding data types, classes and other object-oriented
features with type-checking.
The typescript compiles to plain javascript code.
TypeScript is a programming language developed and maintained by Microsoft.
TypeScript may be used to develop JavaSeript applications for both client side and
server side execution.

Need for TypeScript


JavaScript is adynamic scripting language with no type system. JavaScript provides the
primitive types such as number, string, object but it does not check the datatype of
assigned values. Moreover, JavaScript variables are declared using var keyword which
can not indicate the datatype of the value. So without a type-system it is not casy to use
JavaScript to build complex applications with large teams working on the same code.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


FullStack Web Development Express and Angular
4- 10

The Type system increases the quality of code and readability. It makes the maintenance
of the code easier.
Using TypeScript the developer can catch the erors regarding type-system at the
compile time instead of run time. So that it can be fixcd casily before it gets conplex.
• Another important aspect of using TypeScript is its support for the use of object
oriented features in the scripting language.
Features of TypeScript
1. Portability : TypeScript is a portable because it can be executed on any browser or
operating system. It can run on any environment where JavaScript runs.
2. JavaScript : The code written in JavaScript with valid js extension can be converted
to TypeScript by simply changing the extension from js to .ts.
3. Static Type checking : This feature allows type checking at compile.
4. Support for Library : For developing the TypeScript coding we can se all JavaScript
frameworks, tools and libraries easily.
5. Support for OOP: The TypeScript can make use of various features of
object-oriented programming languages such as classes, interfaces, inheritance and
SO on.
6. Client and Server side Development : TypeScript allows the development of both
server-side and client-side programming.
Advantages
1. It is an open source language with continuous development.
2. It runs on any web browser.
3. The TypeScript code can be called from existing JavaScript code. It can also work
with JavaScript frameworks and libraries without any issue.
4. TypeScript has a support for the latest JavaScript feature from ECMAScript2015.
The ECMAScript specification is a standardized specification of a scripting
language. This standard is meant to ensure the interoperability of web pages across
different web browsers. The 6th edition, ECMAScript 6 (ES6) and later renamed to
ECMAScript 2015. Some of major enhancements of this standard include modules,
class declarations and so on.

Disadvantages
1
Weh browsers do not understand the TypeScript code. we want to run
If TypeScript
code in the web browser then we need to compile it. This compilation process
converts it to JavaScript and then we can see the TypeScript
code running in the web
browser.
TECHNICAL PUBLICATIONS -an
up-thrust for knowedge
Full Stack Web Development 4- 11 Express and Angular

2. does not support abstract classes.


It

3. TypeScript takes a time to compile the code.


4.4.1| Installation
Following are the steps to be followed for installing the TypeScript code.
Step 1 :
Installation of Node.js
We first need to installNode.js. We can get it downloaded from https://nodejs.org/en.
The installation can be done on Linux or Windows OS. It has a very simple installation
procedure.
X
Node js

C nodejs.org/en/

aede e
HOME ABOUT DOWNLOADS DOCS GET INVOLVED CERTIFICATION NEWS
SECURITY

Node.js® is a JavasScript runtime built on Chrome's V8 JavaScript engine.

#BlackLives Matter

Newsecurity releases now available for 15.x, 14.x, 12.x and 10.x
release lines

Download

14.16.0 LTS 15.11.0 Current


Recommnended For Most Users Latest Features
SCroll to top
API Docs
Other Downioads| Changelog Other Downioads Changetog API Docs

Qr have alookat the lang Term Suppat (IS schedule

Download node MSI for windows by clicking on 14. 16.0 LTS or 15.11.0 Current
button.
. Ater you download the MSI, double-click on it to start the installation as shown below.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 4- 12 Express and Angular

Nodejs Setup

Welcome to the Node.js Setup Wizard

node The Setup Wirard wil install Node.js on your computer.

Bac Next sCance!

Click Next button to read and accept the License Agreement and then click Install. It
will install Node.js quickly on your computer. Finally, click finish to complete the
installation.
Verify Installation
• In order to verify the installation we have to open a
command prompt and type the
-
following command

Command Prompt

D:\>node -v
v14.15.4

D:\>

If the node.js is successfully installed, then some version number


of the node. js which
you have installed in your
PC willbe displayed.
Step 2: Installation of typescript
We have to install the TypeScript with the help
of the node package manager(npm). The
command can
which be issued at the command prompt is as follows -

npm install -g typescript

TECHNICAL PUBLICATIONS-
an up-thrust for knowlodge
Full Stack Web Development 4- 13 Expres and Angular
-
The screenshot is as follows

GN nprm X
Microsoft Windows [Version 10.0.19843.1415]
l(c) Microsoft Corporation. Al1 rights reserved.
C:\Users\DELL>npm install -g typescript
nt
..]/ extract:typescript: lock using C:\Users\DELL\AppDat

any project.
Thabove command will install TypeScript globally so that we can use :
it in
Now check the installed version of TypeScript using the following command
tsc -v

G CAWindows\system32\cmd.exe X

C:\Users\DELL>tsc -V
Version 4.5.4
C:\Users\DELL>

That's it!. We can now vrite and execute our TypeScript programs.

4.4.2 How to Write TypeScript Program ?


In this section we will develop our first TypeScript program.
Normally for executing the web framework programs web developers prefer to use some
IDE. Most commonly used IDE are Visual Studio Code and Sublime Text2. Ihave used
VisualStudio Code editor for executing the TypeScript programs. It can be downloaded
from the web site https://code.visualstudio.com/
.
The installation procedure of Visual Code Studio is pretty simple. We have to simply
click the Next button and continue with the de fault installation options.

TECHNICAL PUBLICATIONS- an up-thrust for knowiedge


Express and Angular
Full Stack Web Development 4-14
• Now let us begin with writing the TypeScript code
a folder named
Step 1: Create a folder in your local drive. Say I have created
TypeScript Code at my E:\ drive.
a with some name and
Step 2 : Open this folder in Visual Studio Code editor. Create file
a myfirstprog.ts.
extension .ts under this folder. I have created file named

myfirstprog.ts
console.log("Welcome to my First TypeScript Programll!"):

Following screenshot shows it -

mytrstprogts -TypeScript Code Visual Studi. X


Run Temina!
* File Edit Selection Viex Go

T5 myfirstprog.ts Xx

EXPLORER

v TYPESCRIPT CoDE TS myfirstprogts


1
console.log("Welcome to my
First TypeScript Program!!!!"):
) ModuleDemo
TS myfirstprog.ts

IypeScript A
O0AO
Ln 1 Col 59 Tab Sze 4 UTF8 CRLF
0

at the command prompt


Step 3 Now execute above code by issuing following command
:

tsc myfirstprog.ts
-
Following screenshot illustrates it

X
CAWindowsisystem32\cmdexe

E:1TypeScript_Code>tsc myfirstprog.ts
E:1TypeScript_Code>

By this step your typescript code is converted to plain javascript code. That means ou
compiling the myfirstprog.ts the myfirstprogjs file gets generated.

TECHNICAL PUBLICATIONS
'- an up-thrust for knowlodge
Full Stack Web Development Express and Angular
4-15
CAWindows\system32\cmd exe

Directory of E:\TypeScript_Code
|27-12-2021 15:23 <DIR>
27-12- 2021 15:23 <DIR>
27-12-2021 15:23 60 myfirstprog.js
27-12-2021 15:19 58 myfirstprog.ts
2 File(s) 118 bytes
Dir(s) 303,098,732,544 bytes free
E:1Typescript_Code>

Step 4 :
Now we can get the-output of the above program on the web browser. For that
purpose we have create an index.html file by adding new file under typescript-code
folder and call the myfirstprog.js file in it. The code is as follows
index.html
<html>
<body>
<script src ="myfirstprogjs"> </script>
</body>
</html>
Just refer following screenshot
View indexhtm! -TypeScript_Code-Visual
* File Edit Selection Go Run

EXPLORER
<>
index.html
>
index.html
<

V TYPESCRIPT CODE

> ModuleDemo 2 <body>


<) index.html 3 <script src =
"myfirstprog.js"></script>
JS
4 </body>
myfirstprogjs
5 </html>
TS myfirstprog.ts
6

Ln 6. Col Spaces 4
UTF-8 CRLF HTML O

on browser
Step 5 :
Open some web browser and enter the path of the file as URL, right click
window. Select Inspect-> Console. The output can be viewed on Console window.
-
It is as follows

TECHNICAL PUBLICATIONS-an up-thrust for knowledge


Full Stack Web Development 4 - 16 Express and Angular

index.html

O File| E:/lypeScript Codefindex.html Q


& t A

Reading list
Apps

Sources
B1 X
Elements Console
Default levels
top Filter
1
Issue: F1
my
Welcome to First TypeScript Program! !!!

Console Issues What's New

Review Questions
1. What is TypeScript ? Give the advantages and isadvantages of using it.
2. List and explain the features of TypeScript.
3. Write a TypeScript to display a welcome message.

4.5 Type Annotations


The TypeScript is a typed language. We can specify the data type of the variables and
functions. For specifying the type of the variable the syntax is
Variable name:data type
Where data type is any standard data type used in JavaScript. For example
var count: number =100:
Var empName ="Ankita";
var isChecked:boolean = true:

4.6 Variables and Constants


Variable is the storage location at which the value is stored. It is basically a container 10
value in the code. The rules for using variables is as follows -
1. The variable name must be alphabet or numeric.
2 The variable name can not start with a number.
3. The variable name cannot
contain spaces and special
characters except underscoO
dollar sign.

TECHNICAL
PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development Express and Angular
4- 17

Variables can be declared using var and let. The contestant can be declared using const.

var
Thevariable can be declared using the keyword var same as JavaScript. To assign a value
to the variable, use the equal sign.
var studName = "Parth":
let
The let declaration follows the same syntax as var declaration. For example -
let empName = "Archana"
The var declaration has some problems in solving programs, so ES6 introduced let
keyword to declare a variable in TypeScript and JavaScript. The let keyword has some
restriction in scoping in comparison of the var keyword.
Difference between var and let
Var declarations are globally scoped or function /locally scoped. The scope is global when
a var variable is declared outside a function. This means that any variable that is declared with
var outside a function block is available for use in the whole window. For example
for (vari=0;i<5; i++) {

console.log("i=", i);

console.log('Outside the loop: i=,):


The output is
i= 0
i= 1
i= 2
i= 3

i= 4
Outside the loop: i = 5
The let keyword is block scoped. The block is defined within
{ . It means that the

variableionly exists and can be accessible inside the for loop block.
For example -
for (let i= 0;i< 5; i++)
console.log("i=", i);

cOnsole.log("Outside the loop: i=" )

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 4- 18 Express and Angular

The above code gives the error as, we have used console.log statement displaying the value
of ioutside the block.
const
.
Variables declared with the const maintain constant values. Like let declarations, const
declarations can only be accessed within the block they were declared. The const cannot be
updated or re-declared.
This means that the value of a variable declared with const remains the same within its
Scope. It cannot be updated or re-declared. So if we declare a variable with const, we can
:

neither do this
Const name ="Ankita":
greeting = "Prajkta;

4.7 Understanding Interfaces


• Interface is a structure which acts as a contract in our application. That means, interface
defines the syntax that an entity should have.
• The members of interfaces are properties, methods and events.
Syntax
The typical syntax of interface is
interface interface name {
property type: data-type //declare properties, methods or events

Rules for using interfaces


1) The interface should be created using the interface' keyword followed by the name
of the interface.
2) While defining the interface, the data-types of the members must be properly
mentioned.
3) Function interface should only contain the method signature and not implementation.

4) While creating the object for the interface function, it should refer to the
implemented function.
5) While defining the function inside the interface variable type and function return type
should be mentioned properly.
6) While implementing the function which is defined in the interface, the method
signature must be matched properly.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development
4- 19 Express and Angular

Example code for simple interface


Step 1 : crcate a simple TypeScript file with the name app.ts. In this file, we have
We will
defined an interface for the studentType. The Student interface contains two properties -
name and rollno with the data types as string and
number respectively.
app.ts
interface studentType {

name:string,
rollno:number

var students:studentType = {

name:Parth!.
rollno:101

console.warn(students);

Step 2:Now open the command prompt window and issue the command tsc app.ts. This will
created app.js file internally. Execute this .js file as well. Following screenshot illustrates it -

PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL

Microsoft Windows Version 10.0.22621.1555]


(c) Microsoft Corporation. All rights reserved.

E:\TypescriptExamples>tsc app.ts

E:\TypescriptExamples>node app.js
f name: Parth', rollno: 101 }
E:\TypescriptExamples>|

Defining a function in TypeScript Interface


Following code contains an interface, in which we have defined two properties such as
hame and rollno and one function named display_message)
app.js
interface studentType{
name:string:
rollno:number;
display message():string:

var students:studentType ={
name:Parth,
TECHNICAL PUBLICATIONS- an up-thrust for knowledge
Full Stack Web Development 4-20 Express and Angular

rollno:101,
display_message(){return "Hello "+students.name:).

console.wam(students.display message());:
Output

PROBLEMS OUTPUT DEBUG CONSOLE TERMINL

E:\TypescriptExamples>tsc app.ts

E:\TypesriptExamples>node app.js
Hello Parth
E:\TypescriptExamples

Example 4.7.1 Write acode in TypeScript 1o implement the simple arithmetic calculator
application. Make use of interface.
Solution:
app.ts
interface mycalculator {

(anumber,b:number):Number:

function addition(a:numbe,bnumber):number{
console.log('a ="+a);
console.log("b ="+b):
return a+b;
}

function subtraction(anumber,b:number)number{
console.log('a = +a);
console.log("b = +b);
returm a-b;
}
function multiplication(a:number,b:number):number{
console.log('a = +a);
console.log("b = "+b);
return a*b;

function division(a:number,b:number):number{
console.log('a = "+a);
console.log("b ="+b);
return a/b;

console.log("\t******* DEMO OF CALCULATOR ********);

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 4
-
21 Express and Angular

let add:mycalculator = addition;


let result1 = addl(10,20):
console. log("Result of addition = ",result1 ):

let sub:mycalculator = subtraction:


let result2 = sub(20,10):
Console.log("Result of subtraction="result2):

let mul:mycalculator = multiplication;


let result3 = mul(10,20);
console.log("Result of multiplication = "result3);:

let div:mnycalculator = division;


let result4 = div(20,10);
console.log("Result of division = "result4):
Output

PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL

E:\TypescriptExamples\Calci>tsc app.ts

E:\TypescriptExamples\calcinode app.js
*****k* DEMO OF CAL CUIATOR ******
a = 10
b = 20
= 30
Result of addition
a = 20
b= 10
= 10
Result of subtraction
a = 10
b= 20
=
Result of multiplication 206
a = 20
b= 10
= 2
Result of division
E:\TypescriptExamples\calci>l

Review Questions
1. What is interface ? Explain the use of interfaces in TypeScript with suitable example.
2. What are the rules for using interfaces.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Express and Angular
Full Stack Web Development 4- 22

4.8 Implementing Classes


a fundamental
object oriented programming languages like C++ and Java, class is
In
entity which is used to create reusable components.
-
A class contains
Properties
Constructor
Methods
Syntax of declaring class
class <class name> f
field;
method;

Example
class Person {
person id: number;
Properties
person name: string;

gétName:string {
Method
retum "Parth":
}

Jsing constructor
The constructor is a special type of method which is called when creating an object. In
IypeScript, the constructor method is always defined with the name "constructor".
• Example
class Person {

person id: number; Properties


person name: string:

constructor(id: number, name: string) {

this.person id = id; Constructor


this.person name = name;

getName:string { Method
return "Parth":

TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
FullStack Web Development 4- 23 Express and Angular

Creating an object
Anobject is an instance of a class. The object is created using keyword new.

For example -
app.ts
class Person (
person id: number;
person name: string:
constructor(id: number, name: string) {

this.person id = id;
this.person name = name;

Let p1 new Person(101,"Parth")://object p1 is created


console.warn(p1);
Output

PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL

E:\TypescriptExamples\ClassDemo>tsc app.ts
E:\TypescriptExamples\ClassDemo>node app.js
Person person id: 101, person name: "Parth
{ }

E:\TypescriptExamples\ClassDemo>

Inheritance
Inheritance. is a important feature of object oriented programnming in which the child
classes are created by inheriting some of the properties of parent class. The keyword
extends is used to inherit the child class from parent class.
Example
class Person {
pname:string: Parent Class

constructor(name: string) {
this.pname = name;

class Student extends Person


{
Child Class
rollno:number;

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Express and Angular
Full Stack Web Development 4- 24

constructor(name:string,rol:number){
super(name);
this.rollno = roll;
}

display():void {
console.log("Roll Number: ", this.rollno);

console.log("Name: ",this.pname);

}
var stud = new Student("Parth 101);
console.warm(stud);
Output

CAWINDOWS\system32\cmd.

E:\TypeScriptExamples\InheritanceDemo>tsc app.ts
E:\TypeScriptExamples\InheritanceDemo>node app.js
Student { pname: 'Parth', rollno: 101
}

E:\TypeScriptExamples\ InheritanceDemo>

Program explanation : In above program,


We have created two classes namely Person and Student. The Person class contains
the property as pname and the Student class contains the property as rollno.
The Student class inherits the Person class. Hence the object of Student class can
access the property of parent class(i.e. pname) and property of the self class (i.e. rollno);
The keyword extends is used to inherit the base class.

Review Questions
1. What is class ? How to use class in TypeScript ? Explain it
with suitable example.
2. Explain the use of inheritance in TypeScript with suitable example.

4.9 Implementing Modules


module is used to set code written in TypeScript.
A separate
A
module can be defined
.ts file which can contain functions, classes, interfaces.
in a

TECHNICAL PUBLICATIONSD
an up-thrust for
knowledge
Full Stack Web Development 4- 25 Express and Angular

Weusethe prefix export with all the definitions which we want to include in a imodule and
want to access from other modules.

Demo example
Step 1 : We will create calculator.js is a module which contains a
class named Addition.
This class is prefixed with keyword export.
calculator.js
export class Addition {

a: number;
b: number;
b: number) {
constructor(a: number,
this.a = a;
this.b = b;

display(){
console.log ("Addition:" +
(this.a + this.b) );

The above class contains two variables a and b. It also contains one function display).
Step 2: Now we willcreate one JavaScript file for importing the class created in above step.
Definition import : A module can be used in another module using an import statement.
:
Syntax
import { export name } from "file path without extension"
Following file is used for import file.

app.ts
import {Addition) from /calculator;

let obj = new Addition(100, 200);


obj.display();
commands
Step 3 Now open the command prompt and issue the
:

tsc -module commonjs app.ts


node ./.app.js

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


FullStack Web Development Express and Angular
4-26

C Command Prompt

E:\TypeScript_Code\ModuleDemotsc --module commonjs app.ts

E:\TypeScript_Code\ModuleDemo>node ./app-js
Addition: 309

E:\TypeScript_Code\ModuleDemo>

For compiling the modules we have used following syntax


-module <target> <fle path>
The following can be used as target with the above --module command option :

1. None

2. CommonJS
3. AMD

4. UMD

5. System
6. ES6. ES2015 or ESNext
We have used CommonJS option for execution of JavaScript applications.

Importing multiple classes in a single file

Following example illustrates how to import multiple classes in a single JavaScript file.

Step 1 :
Create a TypeScript program and define two classes namely Addition and
Multiplication

calculator.js
export class Addition {

a: number;

b: nunber;
constructor(a: number, b; number) {
this,a a
this.b = b;

display) {
console, log(Addition:"+ (this, a + this.b) );

export class Multiplication {


a: number;
b: number;

TECHNICAL PUBLICATIONS- an up-thrust for knowiedge


Full Stack Web Development 4- 27 Express and Angular

constructor(a: number, b: number) {

this.a = a:
this.b b;

show()) {
console. log ("Multiplication:" + (this.a this.b) ):

Step 2: Create the app.ts file as follows


app.ts
import {Addition, Multiplication} frorm "/calculator',

let obj1 = new Addition(100, 200);


obj1.display():
let obj2 = new Multiplication(100, 200);
obj2.show():

Step 3: Compile the application

CI Command Prompt X

E:\TypeScript_Code \ModuleDemo>tsc --module comornjs app.ts


E:\TypeS cript_Code\ModuleDemo>node ./app.js
Addition: 300
Multiplication: 20000

E:\TypeScript_Code \ModuleDemo>

Review Question
1. Write a sample application in TypeScript to demonstrate the use of
moules.

4.10 Understanding Functions


Functions are basic building blocks of any javascript document. It makes the code
reusable, readable and maintainable

Syntax
-
The function can be defined as follows
function function name([arg1, arg2,
.., argN) {

Ibody of function

TECHNICAL PUBLICATIONs- an up-thrust for knowedge


4- 28 Express and Angular
Development
Full Stack Web
-
called as follows
The function can be
name([argument]):
Function
Demo Example
app.ts addition(num1:number,num2:number)
function

num1+num2:
var result =
console.log(result):

addition(10,20);
Output

DEBUG CONSOLE TERMINAL


PROBLEVS OUTPUT

E:\TypeScriptExamples\FunctionDemo>tsc app.ts

E:\TypescriptExamples\FunctionDemo>node
app.js
30
E:\TypeScriptExamples\FunctionDemo

Anonymous function type of functions are


name is called anonymous function. The
The function without the
dynamically declared at runtime.

For example -
anonymous function
let display = function() //This is

console.log("Welcome");

display(): //call to the function -


function. For example
We can pass the parameters and return type to the anonymous
let addtion = function(a:number, b:number):number

return a+b;

console.logladdtion(10,20);
lamnbda
Arrow function calledas
also
The fat arrowfunction => is used for anonymous function. They are
functions.

TECHNICAL PUBLICATIONS. an up-thrust for knowedge


Full Stack Web Development 4- 29 Express and Angular

Syntax
....
((arg1,arg2, argN|) => expression { I/function body}
By the use of => arrow we need not have to use the keyword function
For example -
let addtion = (a:number, b:number):number =>

return a+b:

console.log(addtion(10,20);

Review Question
1. Explain the arrow function in TypeScript with suitable example.

Part Il : Angular

4.11 Basics of Angular


Angular is a typescript based free and open source web application framework led by
the Angular team at Google and by a community of individuals and corporations.
Angular 10+ is a JavaScript framework which is used to create single page
applications(SPAs). The single page application is a kind of application which
dynamically rewrites the current page rather than loading entire new pages from a
server. The SPAs provide the user a very fluid, reactive and fast experience.
Angular is completely based on components. Due to which the applications created in
Angular give the reactive speed.
The Angular applications are created with the help of HTML and TypeScript.
Features of angular
1. Support for multiple platforms : Angular is a cross platform language. It allows the
developers tocreate desktop applications and progressive web applications
2. High speed web applications:Angular applications are fast and load quickly with
new component router. Angular is specially used as a front end web development for
the programming languages like Node.js, .Net, PHP, Struts, Spring and other servers
for instant rendering by just using HTML and CSS.
3. Productivity : Angular uses template syntax and command-line tools for adding and
testing the components. This enhances the productivity of Angular.
:
4. Localization One of the best features of Angular l0+ is that the latest angular
version supports for merging of multiple translation documents which could only
load one file in the previous versions.

TECHNICAL PUBLICATIONS- an up-thrust for knowedge


Full Stack Web Development 4-30 Express and Angular

5. Dynamic development : Angular team releases two versions in a year. This helps
the developer to have handy and updated functionalities cach time along with cach
new release.
6. Full stack development : The full stack development is a buzzword that start-up
companies use in this modern of software development. Angular is a complete
framework of JavaScript. It provides testing, animations and accessibility.

Review Question
1. What is angular ? List and explain its features.

4.12 Angular CLI


The Angular CLI is a command-line interface tool that we use to initialize, develop,
scaffold and maintain Angular applications directly from a command prompt or terminal.
It provides some commands and schematics which help us with faster code generation.
Most of the frameworks and applications normally come with CLI.
We can installAngular with the help of Angular CLI.
How to install Angular ?
Step 1: Install Node.js

Step 2: Update npm

While installing the node.js, the npm(node package manager) gets installed. Angular
requires NPM V6.11l or later. Hence we have to check the version of npmn by issuing following
command on the command prompt window.

S Command Prompt X
Microsoft Windows [Version 10.0.19043. 1415]
I(c) Microsoft Corporation. All rights reserved.

C:\Users\DELL>npm -v
6.14.10
C:\Users\DELL>

If you don't have the latest version of NPM, then update it using the following command on
Windows.
npm install -g npm

TECHNICAL PUBLICATIONS- an up-thrust for knowiodgo


Full Stack Web Development 4 - 31 Express and Angular

Step 3: Now install the Angular CLI. For that purpose create a folder in which we want to
install the Angular. Ihave created a folder named AngularDemo in E: drive.

npm

C:\Users\DELL>e:

E:1>mkdir AngularDemo

E:\>cd AngularDemo
E:\AngularDemo>npm instal1 -g @angular/cli
..] | loadDep:ssri: sill resolvewithNewModule balanced-ma

Step 4: We have to check version of installed Angular CLI by issuing the command
ng -
-version
os Command Prompt
how to change this setting, see https://angular. io/analytics. No
+ @angular/[email protected]
ladded 183 packages from 134 contributors in 290.655s

E:\AngularDemo>ng --version

Angular CLI: 13.1.2


Node: 14.15.4

4.13 Creating First Application in Angular


Now create workspace folder for the Angular application.
a I
have created a folder first
-
as
project using ng new command. It is follows
ng new first-app
The answer toadd Angular routing and stylesheet format is css. Now change directory
is y

to the first-app folder and issue the following command at the command prompt window

ng serve -o
TECHNICAL PUBLICATIONS an up-thrust for knowledge
Full Stack Web Development Express and Angular
4-32
-
Following screenshot illustrates it as

G Windows Powershel
E:\AngularDemo> cd first-app

E:\AngularDemo\first-app>ng serve -o
N Browser application bundle generation complete.

Initial Chunk Files |Names |Raw Size


vendor.js vendor
polyfills.js | polyfills 38924 KÊ

styles.css, styles.js | styles 212.52 KÊ

main.js main 3.58 KE

runtime.js runtime 6.35 «6

| Initial Total |
2.68 MB

Build at: -
Hash: Time: ms

**Angular Live Development Server is listening on localhost:4200, open your browser on ht


tp://localhost : 4200/ **

Compiled successfully.

The -o indicates to open it automatically in the default browser.


Use NPM command npm start to build an application. Internally, it uses ng serve
command only. Open a browser and navigate to http://localhost:4200 to see the application
home page. The http://Mlocalhost:4200 is the default URL of an Angular application created
using Angular CLI. Note that here 4200 is a port number on which Server is running.

A FirstApp

0 localhost4200

O
A Welcome

A
+

first-app app is running!

Resources
Hee are some links to help you get started

Learn Angular > <) CUDocumentation >


Angular Material >

Angular Blog > Q Angular Devlools )

Next Steps
What do you want to do next with your app?

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


Full Stack Web Development 4-33 Express and Angular

Note that this is a default page. This script is present in the src folder in the
.

app.component. html file. This is a view file. We normally edit this file and the html script as
per our requirements.

4.13.1 Angular Lifecycle


of different stages it goes through
In Angular, every component has a life-cycle, a number
from initializing to destroying. The view of the main component is rendered in index.html file
using <app-root>. The <app-root> is specified using selector. In the module.ts file using the
annotation @NgModule the component is specified in the declarations section.
Step 1 :
Angular browser displays the index.html file on execution of Angular app. We
normally say that “Angular renders your app"
In the index.htmlfile, there is only one element <app-root></app-root>.

Step 2 :
The <app-root> is defined as selector. In src->app folder. Just open the
app.component.ts. This file contains the selector as follows

@Component({
selector: 'app-root!,
templateUrl: '/app.component.html,
styleUrls: [./app.component.css]
)
Step 3: Inside the app.module.ts file the specification for AppComponent is mentione.

import { AppRoutingModule } from /app-routing.module';


import { AppComponent } from '/app.component';
import { WelcomeComponent } from '/welcome/welcome.component';

@NgModule({
declarations: [

AppComponent,
WelcomeComponent
1,

Step 4: This is the flow of execution Angular app. This app can be displayed in the browser
window when we issue the command ng serve -0 on command prompt or terminal
window.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development
4-34 Express and Angular

4.13.2 Understanding and Using ngModule


Angular modules consolidate components,directives and pipes into cohesive blocks of
functionality.
• For defining the module we use the ngModule.
Every Angular application has at least one NgModule class, the root module, which is
conventionally named AppModule and resides in a file named app.module.ts.
An NgModule is defined by a class decorated with @NgModule(0. The @NgModule()
decorator is a function that takes a single metadata object, whose properties describe the
module.
Just refer following screenshot for ngModule

TS app.module.ts X

STe app ) TS app.moduie ts ) AppModule


1 import { Ng"odule ) from 'angular/core';
2 import {
Browserodule ) from 'angular/platforn-browser';
3
inport { AppRoutingodule } from './app-routing.module';
5 inport ( AppComponent from ./app.component';
inport { WelcomeComponent } from './welcome/welcome. component';
7
vgModule({
declarations: [

16 AppComponent,
11 WelcomeComponent
12
13 inports: [
14 Browserodule,
15 AppRoutingodule
16
17 providers: [),
18 bootstrap: [Appomponent]
19
20 export class Appodule {}
21

Following are the metadata options used in NgModule


Providers: It isan array of injectable objects available.
declarations : It is an array of directives, pipes and components that belong to the current
NgModule.
imports : It is an array of Other modules whose exported classes are needed by component
templates declared in this NgModule.

TECHNICAL PUBLUCATIONS- an up-thrust for


knowledge
Full Stack Web Development
4- 35 Express and Angular

exports : of declarations that should be visible and usable in the component templates of other
NgModules.

bootstrap : This is main application view called root component which hosts all other apps
views only. Only the root NgModule should set the bootstrap property.

4.14 Angular Architecture


The main building blocks of Angular architecture are - (Refer Fig. 4.14.1l)
1. Modules
2. Template

3. Components
4. Data Binding
5. Directives
6. Metadata
7. Injections and Services.

Directives metadata
Modules
Module Module Template
Components Services
Property Event
Binding
metadata Binding
Module Module
Values Functions
Components
Injections

Services

Fig. 4.14.1 Angular architecture

Let us discuss them one by one


1. Modules
as AppModule. It provides
Every Angular App has a root module which is called
bootstrap mechanism that launches the application.
o Organizing your code into distinct functional modules helps in managing the
development of complex applications.
we need to register that
If we want to use another custom Angular module, then
module inside the app.module.ts file.
many functional modules.
o An app typically contains
TECHNICAL PUBLICATIONS- an up-thrust for knowedge
Express and Angular
Full Stack Web Development 4-36

2. Template
witlh Angular Markup and modiv
Template is basically used to combine HTML
HTML element before displaying them.
directives provide program logic and binding markup which connccts
Template
application data and DOM.
-
this
Typically in out Angular App the template looks like
<div style=text-align:center">
<h1>
//code for data binding
</h1>
</div>
3. Components
a class which basically contains the
The component in the application defines
application logic and data.
page is in
The application logic is normally written in TypeScript format and view of the
HTML template.
• A component controls a display of screen called a view.
Every Angular app has at least one component which is known as root component
which connects the component hierarchy with the page Document Object Model(DOM).
4. Data Binding
There are two types of data bindings -
1. Property Binding : This type of binding allows to pass the interpolated values from
application data to HTML. The interpolated values are specified in {{ and }}. bracket
pair. For instance - the student.name is interpolating value.
<p>Name: {{ student.name }}</p>

2. Event Binding: Event binding is used to capture events on the user's end on the apP

and respond to it in the target environment by updating the application data.


5. Directives
The directives extend the HTML with the help of new syntax,
The directives are written using the prefix ng.
These directives attach certain behaviour to the elements. There are two commonly use
directives ng-model and ng-bind.
specified
ng-model : The ng-model binds the value of the HTML Control with the
AngularJS expression value.

TECHNICAL PUBLICATIONS-
an up-thrust for knowledge
Full Stack Web Development Express and Angular:
4- 37

ng-bind : This directive replaces the HTML control value with a specified AngularJS
expression value.
6. Metadata
Metadata means data about data.

Metadata tells Angular how to process a class. It is used todecorate the class so that it
can configure the expected behavior of a class.

The metadata for a component class has a template that defines a view.
The metadata for a service class consists of information Angular needs to make it
available to components through Dependency Injection (D).
7. Injections and Services
• In Angular,
itis a practice for data or logjc that it should not be associated with a
specific view. It is created as a service class. Due to this, the data or logic is shared
across Components.
By dependency injection, we mean to allow access to the service by subscribing it. It
acts as a delegate to the service.
• The @Injectable decorator immediately precedes the service class definition. The
decorator provides the metadata that allows our service to be injected into client
components as a dependency.

Review Question
1. Explain the angular architecture with suitable block diagram.

4.15 Angular Components


Components are basic building block element of Angular. The components are
associated with the template and they define different aspects of the user interface.
-
• Each component consists of
An HTML template that declares what renders on the page.
A Typescript class that defines behavior.
A CSS selector that defines how the component is used in a template.

.
TECHNICAL PUBLICATIONS an up-thrust for knowedge
Full Stack Web Development 4-38 Express and Angular

can be viewed as
Typical organized page in Angular App contains multiple components. It
follows -

Navigation- bar component

Sidebar Section component


component

Footer component

Fig. 4.15.1 Multiple components on angular App page

We willcreate a component in a first-app application. Not its time to create a simple app.

There are two ways to create components - the component can be created manually or it
can be created using Angular CLI command. Let us now create a simple component using
Angular CLI method.

Demo Example
Step 1: Go to the first-app folder and issue the following command at the command line. Note
that the name of my component is welcome. You can give any name to the
component.
ng generate component welcome
PROBLENS OUTPUT DEBUG CONSOLE TERMINAL

PS E:\AngularDemo\first-app> ng generate component welcone


CREATE Src/app/welcome/welcome,component.html (22 bytes)
CREATE Src/app/welcome /welcome,component.spec.ts (633 bytes)
CREATE Src/app/welcome/welcome, component. ts (279 bytes)
CREATE Src/app/welcome/welcome.component,css (0 bytes)
UPDATE Src/app/app.module. ts (479 bytes)
PS E:\AngularDemo\|first-app>

TECHNICAL PUBLICATIONs- an up-thrust for knowledge


Full Stack Web Development Express and Angular
4- 39
On issuing this command the folder named welcome gets created inside the src->app
folder of your project. The project explorer window is as shown below

EXPLORER

FIRST-APP

>angular
>VSCode
>node_modules
V src
app
welcome
# welcome.component.css
( welcome.component.html
TS welcome.component.spec.ts
TS welcome.component.ts
TS app-routing.module.ts

# app.component.css
app.component.html
TS app.component.spec.ts
TS app.component.ts
TS app.module.ts

Note that it creates four files welcome.component.css, welcome.component.html,


welcome.component.spec.ts and welcome.component.ts

Step We will keep our app.component.html file very simple. Delete everything from it
2: following code
which comes by default from the Angular framework and simply add
to it.
app.component.html
<h1>Hello </h1>
it as follows. The bold-faced code
Step 3 :
Now open welcome.component.ts file and edit
component.
shows the modification in the default .ts file of

TECHNICAL PUBLICA TIONS-an up-thrust for knowledge


Full Stack Web Development 4- 40 Express and Angular

import { Component, Oninit} from'@angular/core;

This selector name will be used in


@Component({ app.component.html file (Refer step 5)
selector: 'app-welcome,
templateUd: '/welcome.component.html,
styleUrls: [/welcome.component.css']
})
export class WelcomeComponent implements Oninit {

constructor() {}

ngOninit(): void {

currentUser: String ="Anuradha"

Step 4: Open welcome.component.html file and edit the code in it as follows


-

welcome.component.html

<p>welcome {{currentUser}}<p>

Step 5 :
Now open app.component.html file and edit it with the selector name of the
component.

app.component.html

<h1>Hello</h1>
Kapp-welcome><Japp-welcome>

Step 6 : Now open the command prompt and issue the command
ng serve-o

The application will get compiled and the browser window will get opened. up. The
welcome component will be added to it.

-TECHNICAL PUBLICA TIONS - an up-thrust for knowledge


Full Stack Web Development
4- 41 Express and Angular

Here is the output

A FirstApp X

) localhost 4200

A
Hello
welcome Anuradha
+

If you want to add multiple time the same component, then simply edit your
app.component.html file as

app.component.html
<h1>Hello </h1>
<app-welcome> </app-welcome>
<app-welcome></app-welcome>
<app-welcome></app-welcome>
-
The output will be

A FirstApp X

O localhost:4200

A
Hello
welcome Anuradha
+
welcome Anuradha

welcome Anuradha

TECHNICAL PUBLICATIONS- an up-thrust for knowiedge


Full Stack Web Development 4- 42 Express and Angular

Review Question
1. Give the sample layout of the Angular application with multiple components.
Explain how to create and use thecomponets in Angular:.

4.16 Expressions
Angular evaluates expressions and then can dynamically add the results to
a web page.
as -
Expressions are encapsulated blocks of code inside brackets follows
{{ expression }}
For example
{{2+3 }} //output: 5
{{Java' + 'Program' }} /loutput: JavaProgram
Step Create a folder with suitable folder name using ng new folder-name
1:
Step 2 :Open the app.component.html file under src/app folder.
app.component. html
<h1> Demo of Expression </h1>
<h4>Addition of 10 and 20 is:</h4>
{{10+20}}
<br/>
<h4>Addition of two strings '1' and 2' is:</h4>
K{1+2)}
Output

The output can be viewed on the web browser as follows -

A Expression-App

O localhost4200 A

Demo of Expression
Addition of 10 and 20 is:

30 +
Addition of two strings '1' and '2 is:

12

TECHNICAL PUBLICATIONSan
up-thrust for knowledge
FullStack Web Development 4 - 43 Express and Angular

4.16.1 Pipes
Pipes are used to transform the data. That means pipes take data as input and are getting
transformed into another format. The pipes are written using pipe operator which is denoted by
|. The pipe can be applied to any view or template and to any data input.

Built-in Pipes
1. Lowercase 2. Uppercase
3. Currency 4. Date

5. JSON
Demo Example
Let us understand this with demo example
Step 1:
Create a folder using some suitable name. I have created a folder by a name pipe
demo using the command ng new pipe-demo.
Step 2: Open the app.component.ts file and create a student array as follows -
app.component.ts
import { Component } from '@angular/core;
@Component({
selector: 'app-root,
templateUrl:'/app.component.html,
styleUrls: [/app.component.css]
})
export class AppComponent {

student ={
roll:101,
name:'Anuradha',
city:Pune',
fees:10000,
DOB:09/01/1980'

Step 3: Now open the view page i.e. app.component.html and edit it as follows by using
built in pipes
app.component.html
<h1> Welcome</hl>
<div style="font-weight:bold;">
Name in lower-case: {{student.name lowercase }}

</div>
<divstyle ="font-weight:bold;">

TECHNICAL PUBLICATIONS - an up-thrust for knowiedge


Full Stack Web Development 4- 44 Express
andAngular
City in upper-case: {{student.city |uppercase }}

</div>
<div style="font-weight:bold;'>
Date of Birth: {{student.DOB date }}
</div>
Kdiv style-font-weight:bold;'>
Fees: {{student.fees currency:INR}}
</div>
Step 4: Open the command-prompt and issue the command ng serve -0. The output can
be
displayed on the browser windowas follows

A PipeDemo
X

0 localhost4200

A
Welcome
Name in lower-case: anuradha
City in upper-case: PUNE
Date of Birth: Sep 1, 1980
Fees: 10,000.00

Review Questions
1. Explain how to use expressions
in angular ? Give example.
2. What is pipe ? Demonstrate
the code for pipes in Angular.

4.17 Data Binding


Data binding views.
is a technique where data is
components andits requires
in synchronous with
Data binding defines the communication
between views. It
dynamic HTML and does not components and its
require any complex programming.

TECHNICAL
PUBLICATIONS.
an up-thrust
forknowledge
Full Stack Web Development 4 - 45 Express and Angular

Types of data binding


There are basically two approaches used for data bindings - One way Binding and two
way Binding. The one way binding is done using interpolation binding, property binding and
event binding. Let us discuss them briefly with the help of demo examples.
1) Interpolation binding
one-way
Using interpolation we can bind the values to the user interface elements. This is
or HTML element. This is
data binding. Because data moves from component to view element
one-directional flow of data.
View
Model using
Interpolation

Fig. 4.17.1 Interpolation binding

Demo example
-
Let us understand this type of binding with the help of example
I have created a folder
Step 1: Now create a workspace folder for the Angular application.
-
binding-demo using ng new command. It is as follows
ng new binding-demo
y css.
The answer to add Angular routing is and stylesheet format is
Step 2 : Now change directory to the binding-demo folder. Go to sre->app folder and open
the file app.component.ts. Add two data member roll no and name to the class
AddComponent
app.component.ts
import { Component } from '@angular/core";

@Component({
selector: 'app-root',
templateUrl: './app.component.html,
styleUrls: [./app.component.css']
})
export class AppComponent {

public roll no:number= 101


public name:String = 'Anuradha';

and add following


Step 3: Now open app.component.html file. Delete the entire default code
code to it.

TECHNICAL PUBLICATIONS an up-thrust for knowledge


Full Stack Web Development 4 - 46 Express and Angular

app.component.html
<h1 style="text-align: center;"> WELCOME</h1>
<h2 style="text-align: center;">Roll no: {{roll no}}</h2>
<h2 style="text-align: center;">Name: {{name}}</h2>
Step 4: Now open the command-prompt window and issue the command ng scrve -o. The
browser window will display the output as follows -

BindingDemo X
:
localhost4200

A
WELCOME
+ Roll no: 101
Name: Anuradha

2) Property binding
The property binding is one-way binding in which we can set the properties of the element
to the user interface page. In this binding [ ] is used for data binding. Following example
illustrates it.
View
Model using
Property

Fig. 4.17.2 Property binding

Demo example
Take one image file and save it to src->assets folder. I have with me technical.png file as
a image file which I have saved in src->assets folder.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 4 - 47 Express and Angular

Step 1: Go to src->app folder and open the file app.component.ts. Add the image variable
as follows -

app.component.ts
import { Component } from '@angular/core':

@Component({
selector:'app-root,
templateUrl: /app.component.html,
styleUrls: [./app.conponent.css']
})
export class AppComponent {
public roll no:number = 101;
public name:String = 'Anuradha':
public image = "/assets/technical.png"

Step 2: Open the app.component.html page and set the property value to image.
app.component.html
<h1>WELCOME</h1>
<h2>Rol no: {{roll no}}</h2>
<h2>Name: {{name}}</h2>
<img (src] = "image alt="Logo' style="height:80px;width:150px>
Step 3: Open the command prompt window and issue the command ng serve -o. The output
-
will be as follows

A BindingDemo

O localhost4200

WELCOME
A

+ Roll n0: 101

Name: Anuradha

TECHNIGAL
PUBLICATIONS

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 4- 48 Express and Angular

3) Event binding
case, the event i
The event binding is the flow of data from view to component. In this
component.
triggered on the view or HTML page. The view page sends data to the
View
Model on triggering
triggers event
Event

Fig. 4.17.3 Event binding

In the following application, on clicking the button On the view page


(i.e. app.component.html page), the data is send to the component
Demo example
Step 1: Open the app.component.html page and add following code to it
app.component.html
<h1>WELCOME</h1>
<h2>Roll no: {{roll no}}</h2>
<h2>Name: {{name}}</h2>
<button (click)="display()'>Enroll</button>
Step 2 : open the app.component.ts page and add following code to it.
app.component.ts
import { Component } from "@angular/core:
@Component({
selector: 'app-root,
templateUrl:"/app.component.html,
styleUrls: [Japp.cornponent.css']

export class AppComponent {


public roll no:number = 101;
public name:String ='Anuradha';
display()

alert("you are now Enrolled!! "):

Script explanation :
Byaboye two steps we have created Enroll button on the HTML nage
and on clicking tne
button, "You are Enrolled" message will be displaved

TECHNICAL PUBLICA TIONS® - an


up-thrust for knowledge
Full Stack Web Development 4 - 49 Express and Angular

Step 3: Open the command prompt and issue the command ng serve -o. The output will be

A BindingDemo X

O localhost:4200

WELCOME
Roll n0: 101
Name: Anuradha
Enroll

A BindingDemo

O localhost:4200

localhost:4200 says

A
WE You are now Enrolled!!

OK
+ Roll!

Name: Anuradha
Enroll

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 4-50 Express and Angular

4) Two way binding


Two way binding is a technique in which we can pass the data from vicw to componenM
and from component to view. For example as we type some text inside the textbox, thc sane
text will be be displayed outside the box.

Model View
triggers event at the same time
when event gets triggred

Fig. 4.17.4 Two-way binding


-
Step 1: Open app.module.ts and edit the code as follows
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: '/app.component.html,
styleUrls: [/app.component.css']

export class AppComponent {


public roll no:number = 101;
public name:String ='Anuradha';
public comment:String =";

Step 2: Open app.component.html file and edit the code as follows -

app.component.html
<h1>WELCOME</h1>
<h2> Roll no: {{roll no}}</b2>
<h2>Name: ({name}}</h2>
Enter your Comments: <input |(ngModel)]="comment' type=text">
<hr/>
<p>You have entered...</p>
<h4>{{oomment}} </h4>
Script Explanation: Inabove script we have used input textbox,
using ngModel directive
we are binding the contents
of textbox with the variable comment, And below this text box
inside the paragraph element<p> we are interpolating(using
display the contents of the textbox simultaneously as we
{0})
comment the variable to
type it.This illustrates the two-way
binding process.
Step 3: Open the app.module.tsand import
FormsModule to it. In the following code, bold
faced code indicates the modifications
app.module.ts
import { NgModule } from '@angular/core;

TECHNICAL PUBLICATIONS-
an up-thrust for knowledge
FullStack Web Development Express and Angular
4-51
import { BrowserModlule } from @angular/platform-browser:
import { FormsModule } from '@angular/forms':
import { AppRoutingMoclule } from'/app-routing.module:
import { Appomponent } from "/app.component':

@NgModule({
[
declarations:
AppComnponent

imports: [

BrowserModule,
AppRoutingModule,
FormsModule

providers: (],
bootstrap: [AppComponent]

export class AppModule {}


ng serve -0. The browser
Open the command prompt window and issue the command
:
Step 4
will display the output. Just type some text in the textbox. Note that as you type in
the textbox, the same text willappear on the same HTML page below your textbox.

A BindingDemo X

O localhost:4200.

WELCOME
+ Roll no: 101
Name: Anuradha
Enter your Comments: Brillant Student!

You have entered..

Brilliant Student!!!

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Express and Angular
Full Stack Web Development 4-52

Review Question
binding in Angular.
List and explain various types
of
1.

4.18 Built-in Directives


in ths
Directives is a technique in Angular that adds additional bchaviour to the elements
Angular applications.
There are three different types of directives -
1. Components 2. Structural directives 3.Attribute directives

4.18.1 Structural Directives


The most commonly used directives are structural directives. These are directives that
change the DOM layout. Note that DOM stands for Document Object Modeling.
With the help of structural directive the elements can be added or removed from DOM.
The structural directive's name always starts with an asterisk(*) prefix.
There are three most popularly used structural directives
Nglf
NgFor
NgSwitch
Let us discuss these in detail.

4.18.1.1 nglf Directive


It is used to create or remove a part of the DOM tree
depending on a condition.
Syntax
<div nglf="condition'>Content to isplay vwhen condition is true.</div>

Demo Example
Step 1: Create a workspace using following command ng new directive-denmo

Step 2: Edit app.component.html as follows


app.component.html
<button (click)="show = show'>
{{show ? 'Click to Hide': 'Click to show'}}
</button>
<br>
<h1>
<div *nglf="show>Welcome user!l</div>
</h1>
TECHNICAL PUBLICATIONS-
an up-thrust
for knowledge
Full Stack Web Development 4 -53 Express and Angular

Step 3: Edit the app.component.ts as follows


-

app.component.ts
import { Component } from 'a@angular/core';
@Component({
selector: 'app-root,
templateUrl: '/app.component.html',
styleUrls: [./app.component.css'|
})
export class AppComponent {

show: boolean true;

Step 4: Execute the above code using ng serve -o

DirectiveDemo X

) localhost:4200

Click to Hide

Welcome user!!
+

Now click the 'Click to Hide' button

DirectiveDemo X

localhost:4200
O
Click to show

A
A

TECHNICAL PUBLICATIONS- an up-thrust for knowedge


Full Stack Web Development 4 - 54 Express and Angular

nglf Directive with else block

If the expression evaluates to false, then the template for else block is used.

The else binding points to an <ng-template> element labeled #clscBlock. The template
can be defined anywhere in the component view, but is typically placed right after nglf. Let us
understand its usage with the help of example.
Demo Example

Step 1 : Create a workspace using following command ng new dircctive-demo


Step 2: Edit app.component.html as follows -
app.component.html
<button (click) =show = 1show'>
{{show ? 'Click to Hide': Click to show}}
</button>
<br>
<h1>
<div *nglf="show; else elseBlock'>Welcome user!!</div>
<ng-template #elseBlock>Good-bye!!</ng-template>
</h1>
-
Step 3: Edit the app.component.ts as follows
app.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-root,
templateUrd: "/app.component.html,
styleUrls: [./app.component.css]

export class AppComponent {

show: boolean = true;

TECHNICAL PUBLICATIONS-an
up-thrust for knowledge
Full Stack Web Development Express and Angular
4- 55

Step 4: Exccutethe above code using ng serve -o

A DirectiveDemo X

O localhost4200

Click to Hide

A
Welcome user!!
A
+
Now click the 'Click to Hide' button

A DirectiveDemo X

localhost:4200

Click to show

A
Good-bye!!
A

4.18.1:2 ngfor Directive


This is a type of structural directive that shows the template for each item in the collection
or list. The ngFor is prefixed by *. The syntax is

<li *ngFor="let item of items;">...</li>


Demo Example
Following example illustrates how to use *ngFor directive for displaying the list of
students.
is to be created.
Step 1: Go to the folder location in which the application for ngFor
-
is as follows
Open app.component.ts file and edit

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 4- 56 Express and Angular

app.component.ts
import { Component ) from @angular/core'
@Component({
selector: 'app-root',
templateUrl: '/app.component.html,
styleUrls: /app.component.css']

export class AppComponent{


students = |
{roll no:2,name:'Archana'}.
{roll no:4,name:Chinmaya'},
{roll no:6,name:'Soumya'}.
{roll no:8,name:'Swati'}

Step 2: Now open the html file and edit the code as follows -
app.component.html
<h1> List of Students </h1>
Ktable border=5>
<th> Roll No</th>
<th>Name</th>
<tr *ngFor="let student of students;">
<td>{{student.roll no}}</td>
<td>{{student.name}}</td>
</tr>
K/table>
Step 3: Run the above application at the command prompt by issuing
ng serve -0. The web browser will get opened up the command
and the output will be displayed as
follows -

A DirectiveDemo
XX
O localhost4200

List of Students
+ Roll No Name
2 Archana
Chinmaya
Soumya
8 |Swati

TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development
4- 57 Express and Angular
4.18.1.3 ngSwitch Directive
The [ngSwitch] directive on a container specifies an expression to match
against.
The expressions for matching are provided by ngSwitchCase directives on views within
the container. The ngSwitchCase is preceded by asterisk or *.
Every view that matches is displayed.
If there are no matches, a view with the ngSwitch Default directive is rendered.

Demo example
Let us see the example that explains the use of ngSwitch directive.
Step 1: Go to the folder location in which the application for ngSwitch is to be created.
Step 2: Open app.component.ts file and edit is as follows -
app.component.ts
import Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl:'/app.component.html,
styleUrls: /app.component.oss']

export class AppComponent {

counter=3;

as follows -
Step 3 Now open the html file and edit the code
:

app.component.html
<h3> ngSwitch Demo</h3>
<div [ngSwitch]="counter">
<div *ngSwitchCase="1"> 1 is selected</div>
<div *ngSwitchCase="2"> 2 is selected</div>
<div *ngSwitchCase="3'> is selected</div>
3

<div *ngSwitchCase="4"> 4 is selected</div>


<div *ngSwitchDefault > Default value </div>
</div>

TECHNICAL PUBLICATIONS an up-thrust for knowledge


Express and Angular
Full Stack Web Development 4- 58
command
Step 4: Run the above application at the command prompt by issuing the
ng serve -o. The web browser will get opcned up and the output will be displavod
-
as follows

A DirectiveDemo X

localhost:4200

ngSwitch Demo
A 3 is selected

Now if we set counter =99 in the app.component.ts file then the output will be

DirectiveDemo X

O localhost:4200 :

ngSwitch Demo
A
Default value

4.18.2 Attribute Directives


Attribute directives listen to and modify the behavior
of other HTML elements, attribuless
properties and comnponents,

TECHNICAL PUBLICATIONS-
an up-thrust for knowledge
Full Stack Web Development 4
-59 Express and Angular

Many ngModules such as the FormsModule define their own attribute directives. The most
common attribute directives are as follows :
Directive Description
ngModel The ngModel directive binds the value changes in the attached form element with
changes in the data model. Thus we can use ngModel to create two-way data
bindings for reading and writing input-control values.
ngForm The ngForm directive creates a top-level FormGroup instance and binds it to a
<form> element to track aggregated form value and validation status. As sOon as we
import FormsModule, this directive becomes active by default on all <form> tags.
There is no need to add a special selector.
ngStyle This directive updates the style of an HTML element.

Demo example
Step 1: Create a new application by creating a folder using following command
ng new form-demo

Step 2 When we want to use the template form, the first thing which we need to do is to
:

as follows -
import FormModule. Open app.module.ts file and import FormModule
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser;

import { AppRoutingModule } from '/app-routing.module';


import { AppComponent } from '/app.component;

import {FormsModule }
from @angular/forms;
@NgModule({
[
declarations:
AppComponent

[
imports:
BrowserModule,
FormsModule,
AppRoutingModule

providers: []l,
bootstrap: (AppComponent]
})
export class AppModule {}

TECHNICAL PUBLICATIONS- an up-thrust for knowvledge


Full Stack Web Development 4- 60 Express and Angular

Step 3 :
We will write code for creating a form with ngModel. so add following code lo
app.component.html file.

app.component.html
<form #myForm='ngForm (ngSubmit)="submit(myForm.value)">
<div class="form-group">
<label for="firstName">First Name <label>
<input type =text' name="frstName" I(ngModel)] ="irstName" >
</div>
<br>
<div class="form-group">
<label for="lastName">Last Name <label>
<input type =text" name="lastName" I(ngModel)] ="lastNamne" >
</div>
<br>
<div class="form-group'>
<label for="mobileNum">Mobile Number <Mabel>
<input type ="text name="mobileNum" [(ngModel)]="mobileNum" >
</div>
<br> <br>
<button type="submit>Submit Kbutton>
</form>
:

Script explanation
In above code we have created three text boxes and one submit button. On submit button,
we call a method named submit(myForm.value). This method
will display the contents
entered by the user in the input text boxes.
The form-group class is used for each component because encourages proper grouping of
labels, controls, optional help text and form validation messaging.
For cach fieldthe ngModel is specified. The ngModel is a directive which binds input,
select and textarea and stores the required user value in a variable and we can use that variable
whenever we require that value.
Step 4 :
In ts file. we will write submit) and get all input fields values. So let's add following
code to app.component.ts file.
app.component.ts
import { Component } fron @angular/core';

@Component({
selector: 'app-root,
templateUrl: /app.component.htm!,
styleUrls: [./app.component.css']
})
export class AppComponent

TECHNICAL PUBLICATIONS- an up-thrust


for knowledgo
Full Stack Web Development 4-61 Express and Angular

firstNamne:string =";
lastName:string =";
mobileNum:string =":
submit(form:any) {

var firstname = form.firstName:


var lastname = form.lastName;
var mobilenum = form.mobileNum;

alert("First Name: "+firstname+\nLast Name:+lastname+aMobile: "+ mobilenum);

Script explanation:
We have defined the variables for form fields and also defined the submit() method, which
was invoked by the form in app.component.html file.(Just refer step 2)
In the submit) method we are retrieving form field values such as First Name, Last Name
and mobile Number and then displaying them using alert popup box.
Step 5: Execute the above application using ng serve -o command at the command-prompt
or terminal window.

The output can be displayed on the browser as follows when we enter some data in the
form fields.
Output

A FomOenmo

O localhost 420

A First NameSachn localhost4200 says


First Narne Sachun
A Last Name Tencukar LastNsme Tenduiksr
tobie 1234567890
Moble Number 1234567890

Submt

Review Questions
1. List andeyplain diferent types structural directives in Angular.
of

2. Explain the attribute directives in Angular with suitable example

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 4 - 62 Express and Anguler

4.19 Two Marks Questions with Answers


Q.1 What is Express. Enlist the features.
Ans. : Express is web application framework used in node.js. It has rich set of features that help
inbuilding flexible web and mobile applications.
Features of Express
1) Middleware Middleware is a part of program, that accesses to the database and
:

respond to client requests.


2) Routing : Express JS provides a routing mechanism so that it is possible to reach to

different web pages using the URLS.


3) Faster server side development : It is very convenient to develop server side
development using Express JS.
: Express Js makes debugging casier by providing the debugging
4) Debugging
mechanism.

Q.2 Explain the properties and methods of request object.


Ans. : Refer section 4.3.
Q.3 What is TypeScript ?
Ans. : TypeScript is a typed superset of JavaScript. Any valid JavaScript code is basically a

valid code for typescript as well.


TypeScript extends JavaScript by adding ata types, classes and other object-oriented
features with type-checking.
The typescript compiles to plain javascript code.
TypeScript is a programming language developed and maintained by Microsoft.
TypeScript may be used to develop JavaScript applications for both client side and server
side execution.
Q.3 Enlist the features of TypeScript.
:
Ans.
1. Portability TypeScripi is a porlable because it can be executed on any browser or
:

operating system. It can run on any environment where JavaScript runs,


2. JavaScript : The code written in JavaScript with valid js extension can be converted to
TypeScript by simply changing the extension from js to 4s.
3. Static Type checking : This feature allows type checking at compile.
4. Support for Library: For developing the TypeScript coding we can use all JavaScript
frameworks, tools and libraries easily.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 4 - 63 Express and Angular

5. Support for 0OP : The TypeScript can make use of various features of object-oriented
programming languages such as classes. interfaces. inheritance and so on.
Q.4 What is the difference between let and var ?
Ans. : Var declarations are globally scoped or function / locally scoped. The scope is global
when a var variable is declared outside a function. This means that any variable that is declared
-
with var outside a function block is available for use in the whole window. For example
for (var i= 0; i< 5; i+ +) {
console.log("i=", i):

console.log('Outside the loop: i=" i);


The output is
i=0
i=1
i=2
i=3
i=4
Outside the loop: i=5
The let keyword block scoped. The block is defined within
is
. It means that the variable i

only exists and can be accessible inside the for loop block.
-
For example
for (let i = 0;i< 5; i++){
console.log('i= ", );

console.log("Outside the loop: i= ", i);


error as, we have used console.log statement displaving the value
The above code gives the
ofi outside the block.
Q.5 How to write a class in TypeScript?
-
Ans.: A class contains
Properties
Constructor
Methods
Syntax of declaring class
Class <class name>{
field;
method;

TECHNICAL PUBLICATIONS- an up-thrust for knowedge


Full Stack Web Development 4- 64 Express and Angular

Example
class Person {
person id: number;
person name: string:
getName:string {

return "Parth":

Q.6 Write a TypeScript document for creation of object


Ans.: An object is an instance of a class. The object is created using keyword new.
For example
app.ts
class Person {
person id: number;
person name: string;
Constructor(id: number, name: string) {
this.person id = id;
this.person name = name;

Let p1 = new Person(101,"Parth")://object plis created


console.warn(p1);
Q.7 What is Anonymous function? Give an example of it.
Ans. : The function without the name is called anonymous function.
The type of functions are
dynamically deciared at runtime.
For example -
let display = function() //This is anonymous function

console.log("Welcome");

display); /call to the function


Q,8 Explain arrow function in TypeScript
Ans. : The fat arrow function => is used for anonymous
function. They are also called as
lambda functions.

Syntax
(larg1,arg2,., argN]) => expression { //function bodý
By the use of=> arOW we need not have to use the keyword function

TECHNICAL PUBLICATIONS- an up-thrust


for knowledge
Full Stack Web Development Express and Angular
4- 65

For example -
let addtion = (a:number,, b:number):number =>

return a+b;

console.log(addtion(10,20):
Q.9 What is Angular ?
Ans. : Angular is a typescript based free and open source web application framework led by the
Angular team at Google and by a community of individuals and corporations.
Angular 10+ is a JavaScript framework which is used to create Single Page Applications(SPAs).
Q.10 What is the use of ngModule in Angular ?
:
Ans.
Angular modules consolidate components, directives and pipes into cohesive blocks of
functionality.
For defining the module we use the ngModule.
Every Angular application has at least one NgModule class, the root module, which is
conventionally named AppModule and resides in a file named app.module. ts.
Q,11 What are the two types of data bindings in Angular ?
-
Ans.:There are two types of data bindings
1. Property binding This type of binding allows to pass the interpolated values from
:

application data to HTML. The interpolated values are specified in {{ and}} bracket
pair. For instance - the student.name is interpolating value.
<p>Name.: ({ student.name}}</p>
2. Event binding :
Event binding is used to capture events on the user's end on the app
and respond to it in the target environment by updating the application data.

TECHNICAL PUBLICATIONS- an up-thrust for knowtedge


Full Stack Web Development 4- 66 Express and Angular

Notes

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


UNIT V

5 React

Syllabus
MERN STACK - Basic React applications - React Components - React State - Express REST APIs
Modularization and Webpack - Routing with React Router - Server-side rendering

Contents
5.1 MERN Stack
5.2 Basic React Applications
5.3 React Components
5.4 Inter Components Communication
5.5 The props
5.6 React State
5.7 Express RESTAPIs
5.8 Modularization and Webpack
5.9 Routing with React Router
5.10 Server-side Rendering
5.11 Two Marks Questions with Answers
Full Stack Web Development
5-2 React

5.1 MERN Stack


MERN stack is a collection of four technologies that are used to
develop full stack web
applications.
MERN stack comprises of four technologies namely,
M stands for MongoDB which is used for preparing database.
E stands for Express mainly used for developing Node.js web framework.
R stands for React mainly used for developing client side JavaScript framework.
N stands for Node.js which is an open source,,
cross-platform, JavaScript run-time
environment that executes JavaScript code outside a browser.
of
MongoDB, Express.js, and Node.js help you build the
backend of an application, while
React powers the frontend. By learning MERN stack will
help you to become a full
stack developer.
Components of MERN Stack
1) MongoDB : MongoDB is a NoSQL database where each
vWeb
record is a document comprising of key-value pairs React
that are
similar to JSON (JavaScript Object Notation)
objects.
MongoDB enables users to create databases, schemas and
tables. It offers the Mongo shell that provides a JS interface Express
Server
for deleting, querying and updating the records. Node.js

2) Express : Express is a NodeJS framework that simplifies


writing the backend code. Express.js has powerful models for
URL routing (matching an incoming URL with a server
function), and handling HTTP requests and responses. For Database MongoDB
keeping the code precise, ExpressJS offers a range
of
middleware.
Fig. 5.1.1 MERN
stack
3) :
React React is one of the most popular open-source front-end JavaScript
libraries used
for building Web applications. It is used to build User Interfaces page
(U) for single web
application. It allows developers to create large web applications can
that easily change
the data of the page even without reloading the page.
4) Node.js : It is open source JavaScript Runtime environment. It is Fast -
Built on Google
Chrome's JavaScript Engine and has a fast code execution. It allows users run
to code on
the server. It comes with the node package manager or npm,
enabling users to select from
a wide selection node modules or
of packages.

TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development React
5-3

Review Question
1. With suitable block diagram explain the concept
of MERN stack.
5.2 Basic React Applications
Let us start the introduction of ReactUS with a real-world example. Suppose that on a Facebook
page, you click the "ike on some photograph and then by the time you
scroll down the same
page, the like count gets incremented by some number, even
without reloading your Facebook
page. This magic change happens because of our ReactJS!!!

ReactJS is an open source, component-based front end JavaScript library maintained by


Facebook.
This library is responsible only for the view layer of the application. That means this JavaScript
is for building user interfaces.

Features of ReactJS
Virtual DOM:DOM stands for Document Object Model. It also provides a way to update
the content, structure and style of the document. Virtual DOM is a representation of original
DOM. When user updates something on the web application, DOM gets updated. Updating
the DOM is very slow, most of the JavaScript frameworks update the whole DOM which
makes it slower. But actually there is no need to update the whole DOM, instead, these
frameworks should update only the part of DOM that is required to update. This is what the
virtual DOM does. This is why ReactJS's DOM manipulation is much faster than other
frameworks. Due to this property, whenever any change is made in the web application, then
those changes are reflected on the web page within no time.
Components : This feature allows the web developer to create custom elements which can
be reused in HTML.
JSX : JSX is an extension of JavaScript syntax. JSX can be seen as a combination of
javascript and XML. The syntax of JSX is very simple that makes writing components very
easy.
.One way data binding : The ReactJS is designed in such a way that it follows.
unidirectional or one way data binding. That means, data is allowed to flow in one direction
at a time., This helps in achieving greater control over the application. This makes helps in
increasing the efficiency of an application.

TECHNCAL PUBLICATIONS- an up-thrust for knowledge


FullStack Web Development 5-4 React

Installation of ReactJS
Open the command prompt window and issue the command
C:\Users\DELL>npm install -g create-react-app
The installation process will get started. Following screenshot shows it.

os. npm X

C:\Users\DELL>npm install -g create-react-app


...]| refresh-package-json:create-react-app: Eiming action:finalize

Check if the reactJS is installed or not by checking its version


X
Command Prompt

C:\Users\DELL>Create-react-app --version
5.0.0
C:\Users\DELL>

That all, if it shows some version number then the reactjs is installed.

Creating first program


We will create out simple ReactlS application in which we will simply display a "Welcome
User message.
Step 1: Go to the directory in which the first application is to be created. At the command
prompt issue the command
D:\reactDemo>create-react-app firstapp
Note that the firstapp is the name of the first program written in reactjs

TECHNICAL PUBLICATIONS- an up-thrust for knowfedge


Full Stack Web Development
5-5 React

npm X

D:\reactDemo>create-react-app firstapp
Creating a new React app in D:\reactDemo\firstapp.

Installing packages. This might take a couple of minutes.


Installing react, react-dom, and react- scripts with cra-tempiate. ..

•]| loadDep:@babel/types: sill resolvewithNewModule @babel/helper

-
Step 2: Now locate the index.js file which is present inside the src folder. Edit it as follows
index.js
import React from 'react';
import ReactDOM from react-dom';

ReactDOM.render(
<h1> Welcome, user!!</h1>,
document.getElementByld('root')

Step 3: Now open the terminal window or command-prompt window and issue the command
npm start
By this command the web browser gets opened and the output will be displayed.

9 React App X

localhost:3000

Welcome, user!!!
+

TECHNICAL PUBLICATIONS- an up-thrust for knowedge


5-6 React
Full Stack Web Development

Review Questions

1. What is ReactJS ? Enlist the features of it.

2. Write a simple ReactJS application that displays Welcome


user message.

5.3 React Components


are two types of
Components are basic building blocks of any ReactJS application. There
-
components that are created in ReactJS

1. Functional Components

2. Class Component

1. Functional components
Functional components are simple JavaSeript functions. The functional components return the

JSX(JavaScript XML)code to render the DOM tree. Following code fragment shows the functional

component
function Welcome(props) {
return <h1>Welcome {props.name) </h1>;

-
as follows
Alternatively the functional component can be created using arrow function
const Welcome = (props) =>{
return <h1>Welcome (props.name)</h1>;

Note that the function name always start with capital letter.

Demo Example
Step 1: Open the command prompt and issue the following command
D:\reactDemo> create-react-app funcomponent

By this command we are creating a workspace by the name funcomponent in which we will be
creating our function component.

TECHNICAL PUBLICATIONS-an up-thrust for


knowledge
Full Stack Web Development 5-7 React
-
Step 2: LOcate index.js file in the sre folder of your application and edit
itas follows
index.js
import React from react'; Note that the function name's first
import ReactDOM from 'react-dom':
import'./index.css': letter must be in capital

function DisplayStudent(student){
retun <div>
<h2>Student Information....</h2>
<p>
<label>Roll no:<b>{student.Rol}</b></label>
</p>
<p>
<label>Name:<b>{student.Name}</b></label> Here the functional
</p> component is defined.
<p>
<label>phone:<b>{student.Phone} </b><Mabel>
</p> Passing the values to the
</div>; functional component

const element =<DisplayStudent Roll="111" Name = "Chitra" Phone


"1234567890"> </DisplayStudent>
//render this component as Id='root'
ReactDOM.render(element,document.getElementByld('root"):
Step 3: Open the terminal window or command-prompt. Switch to funcomponent folder and
issue the command npm start. The web browser willget opened up automatically
-
and the output will be displayed as follows

9 React App X

localhost:3000
O

Student Information...
Roll_no:111
+
Name:Chitra
phone:1234567890

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 5-8 React

2. Class component
To define the class component we have to first create a class and extend React.Componcnt
class.

Class components are ES6 classes that return JSX. Below, is a class component which is similar
to Welcome function(as given in Functional component) :

class Welcome extends React.Component {


render(){
return <h1>Welcome, {this.props.name}</h1>;

Note that the class component must have the render) methodfor returning JSX.
Demo Example
Step 1: Open the command prompt and issue the following command
D:\reactDemo> create-react-app classcomponent
By this command we are creating a workspace by the name classcomponent in which we will
be creating our function component.
Step 2: Locate index.js file in the src folder of your application and edit it as follows
index.js
import React from react':
import ReactDOM fom 'react-dom';
import'/index.css':
class Student extends React.Component
render(){
returm <div>
<h2>Student Information...<h2>
<p>
<label>Roll no:<b>{this.props.Roll}</b></label>
</p>
<p>
<label>Name: <b>{this.props.Name}</b></label>
</p>
<p>
<label>phone:<b>{this.props.Phone}</b></label>
</p>

</div>

const element =<Student Roll="111" Name ="Chitra" Phone = "1234567890"></Student>


ReactDOM.render(element,document.getElementByld(rOOt');

TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development
5-9 React
:
Step 3 Open the terminal window or command-prompt. Switch to
funcomponent folder and
issue the command npm start. The web browser
willget opened up automatically
and the output will be displayed as follows -

9 React App X

:
O localhost:3000

Student Information...
Roll_no:111
+
Name:Chitra

phone:1234567890

Difference between functional component and class component


Sr. No. Functional component Class component
1. Functional components are short and Class components are complex.
simple, easy to understand.

2. These are plain JavaSeript functions that These are the classes that gets extended
accept props as an argument and return from React.Component.
React element.

3. There is no need to use render) method. It must have render() method returning
HTML.

4. Constructors are not used. Constructors are used as it needs to store


the state.

5. Functional components generally are just Class components are used as container
used for display purp0ses. These components to handle state management
Components are used to handle user and wrap child components.
interactions or state updates.

Review Questions
1. Explain the functional component in React.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 5- 10 React

2. Explain the class component in React.


3 Given the difference beween functional and class components.

5.4 Inter Components Communication


React is a component-based UI library. When the Ul is split into small, focuscd componcnts,
they can do one job and do it well. But in order to build up a system into something that can
accomplish an interesting task. multiple components are necded. Thcse componcnts often nced to
work in coordination together and., thus, must be able to communicate with cach other. Data must
be exchanged among the components.
In this section we will discuss the communication from parent class to child class.

Step 1 : Go to the directory in which the first application is to be created. At the command
prompt issue the command create-react-app <folder-name>
Step 2: Now open the corresponding folder and edit the index.js file as follows
index.js
import React from 'teact':
import ReactDOM from teact-dom;
class Student extends React.Component{
constructor(props){
super(props):

render(){
return <div>
<h2>Student Information....</h2>
<p>
<label>Roll no:<b>{this.props.RolI}<{b></label>
</p>
<p>
<label>Name: <b>{this.props.Name} </b></label>
</p>
<p>
<label>phone:<b>{this.props.Phone}</b></label>
</p>
<p>
<label>Total Marks:<b>{this.props.Marks) </b></label>
</p>
<Marks English={this.props.Engish} Maths={this.props.Maths}
Science={this.props.Science}></Marks>
</div>

TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development 5-11 React
class Marks extends React.Component{
constructor(props){
super(props);

render(){
return <div>
ch3>Marks of Each Subject are..</h3>
<p>
<label>English:<b>{this.props.English} </b></Mabel>
</p>
<p>
<label> Maths:<b>{this.props.Maths}</b></label>
</p>
<p>
<label>Science:<b>{this.props.Science) <b></label>
</p>
</div>

const element =<Student Roll="111" Name = "Chitra" Phone = "1234567890* Marks ="95
English="40" Maths="35" Science="20> </Student>
ReactDOM.render(element,document.getElementByld(root));

Step 3:
Open the terminal window and issue the command npm start. The web browser will
get opened up automatically and the output will be displayed as follows -

React App

O localhost3000

Student Information...
Roll _no:111
+
Name:Chitra
phone:1234567890

Total Marks:95

Marks of Each Subject are...

English:40

Maths:35
Science:20

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 5-12 React

Review Question
1. Write a sinmple React app to demonstrate the communication among 1he components.

5.5 The props


The props stand for properties. Thcse are the arguments that are passed to the rcact componcnts.
Props are passed to components via HTML attributes.
For example consider following HTML script
Const element= <Student course="computer science"/>;

The component receives the argument as props object. The code is


function Student(props) {
return <<h2> Ihave opted for{ props.course}</h2>

The props are basically used to pass data from one component to another.

5.6 React State


Basic concept
The React State is a built in object which contains data or information about the
component. The component's changing state can be represented by this state object. The
change in state can happen as a response to user actions or events.
Every time the state of an object changes, React re-renders the component to the
browser.
The state object is initialized in the constructor.
The state object can store multiple properties.

The setState() function


The setState) is used to change the value of the state object.
State can be updated in response to event handlers, server responses, or prop changes.
This is done using the setState() method. The setState) method enqueues all
of the
updates made to the component state and instructs React to re-render the component and
its children with the updated state.

Demo example
Step 1 :Create a folder with some suitable name. I have created a folder named
statedemo by
the following command
E:> create-react-app statedemo
Step 2: Locate the src folder and edit the index.s file as follows

TECHNICAL PUBLICATIONvS- an
up-thrust for knowledge
Full Stack Web Development 5-13 React

index.js
import React from 'react!:
import ReactDOM frorm 'react-dom';
import './index.css:
class Color extends React.Component {

constructor(props) {
super(props);
this.state = {colomame: "Blue"}:

changeColor()

this.setState({colorname: "Golden"}):

render(){
return (

<div>
<h1>My Favorite Color is {this.state.colorname}</h1>
<button onClick={0=>this.changeColor() } > Click to change color</button>
</div>

const element = <Color></Color>


ReactDOM.render(element,document.getElementByld('root"));

Step 3 : Open command prompt and type the command npm start. The output will be
displayed on the web browser

8 React App X

O localhost:3000 A

My Favorite Color is Blue


Click to change color

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 5- 14 React

Click the button and we get

X
React App +
O localhost:3000

My Favorite Color is Golden


«
Click to change color
+

Program explanation : In above application,


1. We have eited index.js file. The class named Color is a child class
of React
Component.
2. In this class, we have written a constructor. This constructor assigns initial
this.state
with variable colorname as blue.
3. In the render) function of React we have displayed a message using hl tag. Below this
message the button component is
created.
4. On the button click event the state must get
changed. For this purpose, the event handling
function changeColor is writen.
5. In changeColor) function, the state is changed by
using this.setState). The parameter
passed to this function is state variable
colorname with some updated value. Basically,
React provides its own method
setState). The setState)method takes a single parameter
and expects an object which should contain
the set of values to be updated. Once the
update is done the method implicitly
calls the render() method to repaint
the page.
6 Thus when the button is clicked
the color value changes from blue to
Golden.

TECHNICAL PUBLICATIONS -
an up-thrust for knowlodge
Full Stack Web Development 5- 15 React

Difference between props and State


Prop State
Props are immutable. That means once we set State holds data and it can be changed over the
the props can not be changed. time. i.e. States are mutable.
Props can be accessed by child component. State carn not be accessed by child component

Props allow to pass the data from one State holds the information about the components.
component to another.

Props can be used in both functional as well as State can only be used in class components.
class components.

The parent component sets props for the Event handlers generally update state.
children components

Review Questions
1. Explain the concept of React state with suitable web application.
2. What is the difference between props and states ?

57 Express REST APIs


What is API ?

API stands for Application Programming Interface. APIs are a set of functions and
procedures that allow for the creation of applications that access data and features of other
applications, services, or operating systems.
In other words, if you want to interact with a computer or system to retrieve information or
perform a function, an API helps you communicate what you want to that system so it can
understand and fulfil the request.

It is basically software intermediary that allows two applications to talk to each other. For
a
on our mobile phone. we
example -
When we use facebook, send a message or check the weather
ise API.
For example If we want to buy a movie ticket, we go to the online ticket booking site, enter
-

movie name, use credit card infornation, get the ticket, print it. The software that interacts with s
some well known examnlee
to perform all these task is nothing but the API. Following screenshots

of API.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 5- 16 React

Login with one of these available social accounts..

Howyou'llpay
GitHub

VISA DSCOVER
o
Instagram

Facebook
O
Pay with Other
C Google

in Linkedin

What is REST API?


REST stands for Representational State Transfer. It is a set
of rules that developers follow
while creating their API.

Each URL made by the client is a request and data sent back to the
client is treated as response.
The request consists of,

1. End Point 2. Method 3. Headers 4. Data

(1)Endpoint
The endpoint (or route) is the URL you request. For example -

http://localhost:8082/
(2) Methods

There are various types of methods. But the most commonly used one are as follows -
1) GET 2) POST 3) DELETE
4) PUT 5) PATCH
These methods are basically used for performing CRUD operations. Here C-
stands for Create,
R- stands for Read, U- stands for Update and D-stands for Delete.

TECHNICAL PUBLICATIONSan
up-thrust for knowedge
Full Stack Web Development 5-17 React

Method Purpose
GET For getting the data from the server, this request is used. The server looks for the
data the client has requested and sends it back to the client.

POST This method is used when new resource is to be created on the server. When
client uses this method and provides the data, then the server createsa new entry
in the database and acknowledges the client whether the creation is successful or
not.

PUT and These are the two methods that are used when the client wants to update some
PATCH resource. When PUT method is used, then that means client wants to update
entire resource. And when PATCH method is used, then that means client simply
wants to update small part of the resource.

DELETE This request is used to delete a resource from the server.

There are some software tools such as Postman, that help the client to select the appropriate
method and issue the URL. Following screenshot is of a software tool Postman, using which we
can select appropriate method.

GET http://localhost:8082/employees

GET

POST In this URL, the


lemployees acts as a
PUT
endpoint

PATCH A client Can


select any
DELETE desired method.

COPY

HEAD

OPTIONS

LINK

UNLINK

PURGE

LOCK

TECHNICAL PUBLICATIONS- an up-thrust for knowtedge


Full Stack Web Development 5-18 React

(3) Headers
Header are used to provide authentication and other useful information to client and server. The
HTTP headers are property-value pairs separated by Colons(:).
For example -
"Content-Type: application/json"

(4)Data
The DATA contains information which the client wants to send to the server. While sending the
DATA to the server the methods such as POST, PUT, PATCH or DELETE are used.
It is preferred to send the data in JSON format. The format is,

Property1l:value1,
Property2:value2

Concept of Node JS API


The Node.js script is popularly used to create REST API. We will write the server script in
Node.js. The database is created using MongoDB. The client interface is handled with the help of
Postman.

Request REST
API
Client Using MongoDB
Response Database
Node.js
and Express

Let us understand how to create Node JS REST API with the help of following example
Example Code
Prerequisite : For creating the Node.js Rest APlwe need following software to be instaled in

our machine
1) Postman :
This is an API client. This client software allows us to enter the request in
JSON format and sclect the commands such as GET, POST, UPDATE, DELETE and so
on.

TECHNICAL PUBLICATIONS- an up-thrust


for knowtodgo
Full Stack Web Development 5-19 React

2) MongoDB : This is a database package. We need MongoDB compass to be installed


along with the mongoDB server application. The MongoDB compass is a graphical too
for handling database operations.
3) NodeJS: This is of course used for creating an APIin js file.
Step 1 :Make a new folder in your current working directory for creating Rest API. Here I
am creating a folder named RestApiDemo

Step 2 : Now open the command prompt window and create package.json file using npm init
command. Following screenshot illustrates the same.
At the command prompt simply type the command
npm init
Then hit the enter button. You can add the values of your choice or simply go on pressing enter
key and accept the default value.
npm

p:VlodeJSExanples\RestApiDenonpa init
This utility will walk you through creating a packoge.json file.
It only covers the nost common itees, and tries to guess sens ible defaults.
See npn help init" for definitive docunentat ion cn these fields
and exactly what they do.
Use 'npa instol1 <pke> afteruards to install a package and
save it as a dependency in the package.json file.

Press ^c at any tine to quit.


package name: (restapidemo)
version: (1.0.0)
descript ion: This is ey Rest API Deeo Project
entry point: (index. js) opp.js
test comand:
git repository:
keywords:
outhor: A.A.Puntaæbekar
License: (15)
About to rite to D: Wode JSExaeples\RestApiDemo\ckage.json:

"name": "restapidemo,
"version: "1.9.0,
"description": This is y Rest API Deno Project",
"nain: "app.js,
"scripts: (
1"
"test"
:

"echo \"Error: no test specified\" 24 exit

"author": "A.A.Puntombe kar",


"license: "ISc"

Step 3: Now install some more packages that are required for creating this Rest API
Installation of express module
Issue the following command
prompt:>npm install express

TECHNICAL PUBLICATIONS
-
an up-thrust for knowtedgo
Full Stack Web Development 5-20 React
GA. npm

D: \NodeJSExamples \RestApiDemo>npm install express


...] / rollbackFailedopt ional: npm-session 0521ds5b8d13c60e

Installation of mongodb module


Issue the following command
prompt:>npm install mongodb
Command Prompt
X
D:\ModeJSExamp les\RestApiDemo>np
np AR restapidero1.0.0 install mongodb
No repository field.
mongodbe3.6.4
added 16 packages fro 10 contributors and
found audited 66 packages in 1.215s
vulnerabilities

D:\iode)SExamples\RestApiDemo>

Installation of mongoose module


Issue the following command
prompt:>npm install mongoose
c Command Prompt
X
D:WWodeJSExamples\RestApiDemo>npe mongoose
np install
AR restapideno1.0.0 No repository field.
+ mongooseg5.12.e
added 15 packapges from 85 contributors and
audited 81 packages in 1.841s
|2 packages are looking for funding
run npe fund' for
details
found e vulnerebilities

D:\Wode)SExamples\RestApiDemo>

Installation of nodemon
Issue the following command at the command
prompt
prompt:>npm install -g nodemon -save-dev

TECHNICAL PUBLICATIONs- an
up-thrust for knowledge
Full Stack Web Development 5-21 React

npm

D:\NodeJSExamples\RestApiDemo>npm install -g nodemon -save-dev


-) \ fetchMetadata: Gil] reso lvetithtieModule [email protected] checking installatble

you have
The sample package.json file will show you all these dependencies of the modules
installed just now
package.json
-
J X
package Notepad

File Edit Format View Help

"name": "restapidemo",
"version": "1..0",
"description" "This is my Rest API
:
Demo Project",
"main": "app.js",
"scripts" :: {
"start" "nodemon app.js"
"author": "A.A. Puntambekar",
"license": "ISc",{
"dependencies":
"express": "^4.17.1",
"mongodb": "A3.6.4",
"mongoose": "5.12.0"

Ln 1, Col
1
100% Unix (LF) UTF-8

as I save any changes


Note that added following line in package.json file so that as soon
Ihave
to run the app.js file every time.
the file, the output gets reflected immediately. need not have
I
in

"start":"nodemon app.js"
your main server in a file named app.js.
Step 4 :Now create

TECHNICAL PUBLICATIONs- an up-thrust for knowledge


Full Stack Web Development 5- 22 React

app.js
const express = require('express'):
const mongoose = require('mongoose);
URL for the database
url = 'mongodb://localhost/EmployeeDB'; name

const app = express(): Connecting to MongoDB database


mongoose.connect(url, {useNewUrlParser:true)) using Mongoose package

const con = mongoose.connection //getting the connection object

con.on('open'.() =>{//on opening the connection, connecting with database


console.log(Connected to Database')
})

app.use(express.json()
const employeeRouter = require(./routes/employees') //initial endpoint
app.use(/employees,employeeRouter)
app.listen(8082,. () =>{
console.log("Server Started!!")
})
Step 5: Create a folder named routes. Inside the routes folder create a file named
employees.js. This file willhandle the GET and POST requests of REST API. Using
POST request we can create the APl by inserting the data into the database. The GET
request will retrieve and display the data from the database. Thus routing GET
of and
POST requests is done in this file.

employees.js
const express = require(express);
const IOuter = express.Router();
const Employee= require(./models/employee'); This is a router program
that routes on receiving the
particular type of request
rOuter.get('/, async(req,res) =>{
try {
const employees await Employee.find() Handling GET Command
res.json(employees) issued by the client, and using
}
find(), displaying data present
catch(err) { in the Employee database
res.send('Enor is: '+err)
}

TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Weh Development 5-23 React

router.post(/, async(req,res) => {


Handling the POST request. The data is
const employee = new Employee({ received here from client. Hence we use
req.body followed by name of the data
name: req.body.name,
field
designation: req,body.designation

try {

const e1 = await. ermployee.save();


ros.json(e1);
}

catch(err)
res.send('Error is: '+err)
}

})
module.exports = router
Step 6: Now create another folder named models. Inside models foider create a file named
employce.js. This file will describe the Schema. The fields of the document are
described inthis file along with data type and some other description is mentioned in
this file. Note that the schema is specified in JSON format.

employee.js
const mongoose=require('mongoose')
const employeeschema = new mongoOse.& .Schema( {
name: {

type: String,
Preparing the schema
required: true
for the database
}.
designation: {
type: String,
required: true

})
mongoose.model('Employee,employeeSchema)
module.exports
Step 7 :For better understanding, the folder structure of
this project can be viewed in the

following explorer window

TECHNICAL PUBLICATIONS- an up-thrust for knowedge


Full Stack Web Development 5-24 React

RestApiDemo
models
employee.js

node_modules
routes

employeejs
appjs

package-lockjson
package.json

Step 8: For getting the output, Open the command prompt window and issue the following
command.
DANodeJSExamples\RestApiDemo>nodemon run start
You should get the "Server started" and "Connected to
Database" messages
Command Prompt- nodemon rn start D X
A
D:\Node)SExamples\ResttApiDemonodemon run
nocemon] 2.6.7
start
ocemcor, to
esta: a ay enter rs
Ioodeeor Stting patr(s)
odeo eitg tats0s 5,cjs,7son
nodesor] sting node run start epp.js
(node:13844) iarring: Accessing non-existent -property MongoError
te exports insice circular dependency of nodul
KUse node --trace-Ernings to shod
(node:13844) Deprecatioridarning: current here the warning was created)
Server Discovery and Honitoring en
lgine is depreceted, and ill be resoved
in a future version. To use the ne
Server Discover and onitorig enginE, pass option { useunifiedTopology:
rue } to the MongoCliet constructor. t
Server Started!1!
Cornected to Database

Now, Open the Postman and click on Create


Request. Select the POST command issue the
URL as
http:/Mocalhost:8082/emplovees
And then click on Send button

TECHNICAL PUBLUCATIONS-an
up-thrust for knowtedge
Full Stack Web Development
5-25 React

FOST hriptocitont8081fempljees
Send
Parme Attorttion peranet teret ferts Satti Coekla
mdats fom rtenendsd bnr9rntg Bentty

"name: "Anktta".
*desifnatíon': CEO"

Poty Coolries Headers (7) et Re

Once we hit the send button we get the result by generating the unique id for the data which
we have inserted. It can be viewed as follows,

F Me Hete

Horrs Wbrkspaces Raports Erolors

POST otnmoes Sord

Parawa Aorton Headory

Oanebdt nnna

Dody Cocktes Test t

Vsual

*1a: "adcta15stafssa
*dasigattan: "CEO*

4Fd ad bgtca

In this, manner we can insert more data by selecting the Post command. This data is sent to the
app.js server and then getting stored in the MongoDB database.
Inorder to retrieve data being stored, we can use GET method on Postman client and see the
complete data in the form of JSON structure.

Params Headers Pragut Sou

ode CaoKC endorn

14: 04aSStaDal
"deaigatian: ag".

We can verify the data by opening the database created in MongoDB

TECHNICAL PUBLICATIONS. an up-thrust for knowedge


React
5- 26
Full Stack Web Development
MooCopes-ahoe2701TRpkveLmsv

EvckeeDl eoys
Documes hoc
EmployeeDB.employees Vhdsttan
tmdere
Apomgehon Ernlsh Plan
Schem
Documents oPTONS FIND RESET

Dielaying doeumente 1-3 of3

ADD DATA

te:etlkutt1rem
wirutte1
dexir

sesertlersSNuOSom

employèe details.
manner we have created our REST API for
In this

Review Question
React.js.
Write and explain a simple
application using REST HTTP method APls in
1.

5.8 Modularization and Webpack


technique which helps in code organization by
splitting the code
Modularization is a
program into sub
into smaller parts. The modular architecture
involves breaking down a
programs called modules.
functionality. The module helps to understand
Each module is associated with certain
the entire code.

React is one of the most popular front-end technology


that uses the component structure
where each
for modularizing. React uses something called component structure,
component has its own file. To access the code in the files, we use import and
export.
React
commonly used with
Webpack in react is a
JavaScript module bundler that is

to bundle and manage dependencies.


a
The webpack takes all the necessary JavaScript files, CSS files
combine them into

single bundle that can be loaded by the browser.


the
• fille. Following are
For using the webpack in React we use webpack.config.js
sections of webpack.config.js file - React
application. All the
Entry : The entry refers to the entry point of React entry
The
components branch out from app.js and app.is is found inside index.js.
attribute is defined as follows -

TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development React
5-27
module.exports{
entry:Japp/index.js,

Output : After completing all the processes, the React webpack creates a bundle file.
Using output we can specify the name and location of final output file. For example
module.exports ={
entry:'/app/index.js,
output: {
path: path.join( dirname, "/dist"), I/ the bundle output path
filename: "bundle.js", // the name of the bundle

:
Loader Loader is like compiler, it checks for different types of files and match them
with their appropriate loaders for handling them. For example -
module.exports {
module:
loaders:( {

test: ^.js | jsx)$/,


exclude: /(node modules)/.
loader: 'babel-loader,

There are certain rules used in the module and those are -
test It checks for particular file type(such as js,.css..jsx and so on)
use It specifies a list of loaders used by any specific file type.

exclude It helps the developer to decide which files should not be processed.

Include It helps the developer to decide which files should be processed

For example -

test:/\.css/.
use:('style-loader,'css-loader]
}

o Plugins :
An eflective plugin intertace is included with Webpack. The majority of

webpack's lunctionality makes use of this plugin interface. As a result, Webpack is


more flexible.
:
Mode The mode in React helps developers to use different set ups when they are in
development and production mode.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


5-28 React
Full Stack Web Development
-
devServer
:
It is used to quickly build the applications. For cxample

module.exports =!
devServer: {
inline: true,
contentBase:'./dist!,
port: 3O00
}.
}:

Use of Babel
is
Babel is a JavaScript compiler that converts modern JavaScript code into the version which
compatible with all the browsers. Babel transpiles modern JavaScript for use in React Components.
The transpiler is a tool used to convert source code into another source code of same level.
The main reason we need babel in modularization is that it gives us the privilege to make use
of the latest things JavaScript has to offer without worying about whether it will work in the
browser or not.
Demo Example
Step 1: Create a folder with some suitable name. I have created a folder named
webpack_example. Create an index.html file inside it.
Now initialize npm using npm init -y command

npm
init -y
Step 2: Install react and babel packages
Install react
npm ireact react-dom.
Installing babel
npm i D
@babel/core @babel/preset-env @babel/preset-react babel-loader css-loader html
webpack-plugin sass sass-loader style-loader url-Joader webpack webpack-cli webpack-dev-server

Step 3 : Create webpack.configjs inside your folder(In my case it is webpack example).


Edit the code as follows

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


Full Stack Web Development 5- 29 React

webpack.config.js
const path = require'path"');
module.exports {

entry:./app/inde.js',
output: {
path: path.join( dlirname, "/dist"). // the bundie output path
filename: "bundle.js", // the name of the bundle
}.

module:{
rules:
{

test:/^.js$/,
exclude:/(node modules)/.
use:{
loader:babel-loader,
options:{
presets:["@babel/preset-env", "@babel/preset-react"]
}

}.

test:/\.css/,
use:['style-loader'css-loader']

Step 4 :
Create two folders namely app and dist. Inside the app folder create an index.js file.
The entry point must be index.js. The output will be in bundle.js which will be
created by the webpack in the dist folder.
app
JS anotherModule.js

JS indexjs

# mystyle.css
Step 5: Install jqueryusing npm. Following screenshot illustrates this

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 5-30 React

PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL

PS E:\webpack example> npm install jquery-save


added 1 package, and audited 2 packages in 996ms

found vulnerabilities
PS E:\webpack example>

-
Step 6: The source files in app folder are as follows
index.js
import name from JanotherModule.js':
import '/mystyle.css'
import $ from jquery
import React from Teact
import ReactDOM from teact-dom'

class App extends React.Component{


render(){
retum (

<h1>Welcome {name}</h1>

ReactDOM.render(<App/>,document.getElementByld(root')

anotherModule.js
COnst name = Parth'
export default name;

mystyle.css
body {
background: khaki;

h1{
Rcolor:red;

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development
5-31 React
index.html
<IDOCTYPE html>
<html>
<head>
<title> Modularization and WebPack Demo</title>
</head>.
<body>
<divid="root'></div>
<script src="dist/bundle. js'></script>
</body>
</html>
Step 7: Run and build the application using the command npm run start

PS E:\webpack example> npm run start


> webpack example1.0.0 start
> webpack -w --mode development

Step 8: Open the index.html file in suitable web browser

|9 Modularization and WebPackD X

O File | Ewebpack examplefindex.html

Welcome Parth

Program explanation: In above code,

l) We have created two js files namely index.js and anotherModule.js and one .css file
named mystyle.css. These are bundled together using webpack module and displayed
the output on the browser.

TECHNICAL PUBLICATIONS- an up-thnust for knowledge


Full Stack Web Development 5-32 React

message with the name which is


2) In index.js file we simply render the Welcome"
message, the style is
obtained from anotherModule.js file. For displaying the welcome
applied to hl and body tags and these styles are defined in myStyle.css file. The index.js,
anotherModule.js and myStyle.css files are packed together using Webpack and result is
displayed on the browser.

Review Question
Write a web application of your choice to demonstrate the webpack and
modularization concept.

5.9 Routing with React Router


Routing is atechnique by which the user is directed to different pages based on their action.
ReactUS router is a single page application. The single page application is a web application
that interacts with the user by dynamically rewriting the current page, rather than loading
entire new pages from the server. When a user types a specific URL into the browser and if
this URL path matches any 'route' inside the router file, the user will be redirected to that
particular route.
Most of the popular sites such as Youtube, facebook and Instagram make use of ReactJs for
rendering multiple views via routing technique.
There are two important packages that are used while using React/s routing.
1. react-router It provides core routing components and functions for the React
:

Router application.
2. React-router-dom :This package enables the user to implement dynamic routing
in a web app.
React Router is the core package for the router. React Router DOM contains DOM bindings
and gives you access to React Router by default.
The React Router API is based on following elements :
<Router:The router that keeps the UIin sync with the URL.
<Link> : Renders a navigation link.
<Route> :
Renders a Ul component depending on the URL.
<BrowserRouter>: It is used for handling the dynamic URL.

TECHNICAL PUBICATIONS- an up-thrust for knowledae


Full Stack Web Development
5-33 React

Demo example
index.js
welcome.js

Welcome page routes to

•Contact page routes to


contact,js

Fig. 5.9.1

Step 1 : Create a folder for developing routing application using following command
D:\reactDemo> create-react-app routerdemo

Step 2: Install the package for router using the command


D:\reactDemo\routerdem0>npm instal react-router-dora
Step 3: Inside the sre folder create a js file. Inamed it as welcome.js(note that here the w is
in small letter)
welcome.js
import React from react';
function Welcome(){
return(
<div>
<h1> Welcome User!!!</h1>
</div>
):

export default Welcome


Step 4 :
Again create one more js file inside the sre folder. I have named it as
contact.js(Again note that c is in small letter here.)
contact.js
import React fromn react':
function Contact(0{
return(
<div>
<p> <b>Phone:</b>1234567890 </p>
<p><b>Email:</b>[email protected]<p>
</div>

Lexport default Contact

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 5-34 React

two files
Step 5 :
Locate index.js from src folder. Specify the routes for the above created
welcome.js and contact.js files.
index.js
import React from react;
import ReactDOM from Teact-domn;
import {BrowserRouter, Link, Switch,Route.Routes} from 'react-router-dom';
import Welcome from /welcome';
import Contact from '/contact;

function App(){
return(
<div>
<h1> Router Demo </h1>
<ul>
<i><Link to="/welcomepg>Welcome Page</Link> </i>
<li><Link to="/contactpg'>Contact Page </Link></i>
<ful><Routes>
<Route path="/welcomepg element={<Welcome />} 1>
<Route path=/contactpg element ={<Contact />} />
</Routes>
</div>

ReactDOM.render
<BrowserRouter>
<App></App>
</BrowserRouter>,
document.getElementByld(root
):

Step 6: Open the terminal window and issue the command npm start
React kop

localtyost 3

Router Demo
. WelcoDe Page
+
• Contact Page

TECHNICAL PUBLICATIONS -an up-thrust for


knowledge
Full Stack Web Development 5-35 React

If we click on Welcome Page link then


X
Peact Apo

o.

O localhost 3000/welco.

Router Demo
• Welcome Page

• Contact Page

Welcome User!!!!

If we click on Contact Page then


X
React Acp

localhost.3000/contac...

Router Demo
Welcome Page

Contact Page

Phone: l234567890

Email:abe.xyz@ gmail.com

Review Question
Explain with suitable application for demonstrating routing with React JS.

TECHNICAL PUBLICATIONS an up-thrust for knowledge


Full Stack Web Development 5-36 React

5.10 Server-side Rendering


Server Side Rendering(SSR) is a technique in which the HTML contents of Rcact
application are displayed on the server side before sending it to client.
With SSR the initial page load is faster and it inproves the search engine optimization.
• In server side rendering technique the HTML page is created at the server side with all
the necessary contents of the site and then it is sent back to the user. The user will get
fully render HTML page that contains all the necessary information without having to
wait for and JavaScript or CSS file to load. That means the user who visits the web site
willbe able to see everything much faster than if they were looking at the blank screen
while waiting for JavaScript files to load.
Server-side rendering is used in many popular JavaSeript frameworks, including
Angular and React. There are also other frameworks like Preact, which aims to be a
lightweight alternative to React.
In general, websites that use server-side rendering include social media sites such as
Facebook and Twitter, as well as e-commerce websites like Walmart and Amazon.
• For example - Suppose we have a React application that displays the list of some
articles. When user requests the page, the server retrieves the information from backend
APland uses React's rendering engine to generate HTML content on the server-side.
After creating the HTML file, it is sent to the client along with necessary JavaScript files.
User can immediately display this HTML page on the web browser. After the initial page
load, the application behaves like a typical React application and any additional user
interaction is handled by the client-side JavaScript code. This means that the user experience.
is stillinteractive and dynamic.

The process of utilizing the HTML rendered on the server for a component is called
hydration. The ReactDOM.render) function does not perform hydration but replaces
the entire HTML tree by rendering the component from the scratch. For hydration, we
need to use ReactDOM.hydrate) function.
limport App components
import ( App } fromfcomponents/app;
I/compile App component in #app HTML element
ReactDOM.hydrate(<App/>, document.getElementByld('app) );
This function works exactly the same as the render function but it utilizes
the server-side
rendered HTML instead of rendering the component. However,
it expects the server
side rendered HTML and HTML rendered by the
App component to be exactly the
same. If there is a mismatch, it can lead to
unexpected results.

TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
Full Stack Web Development 5-37 React

Advantages of server-side rerndering


1) Easy Indexing by search Engines As contents are rendered at the server side before
:

sending it to the user, the search engines can easily index and crawl it.
.
2) Fast load time The server side rendering improves the speed of page loading
:
This
improves the overall user experience.
3) Indexing with the use of Social media : Client-side rendering is not supported by
Facebook's Open Graph Protocol or Twitter Cards, for example. If social media sharing is
an important part of marketing strategy, server-side rendering may be a better option.

Disadvantages of server-side rendering


1) Increased burden on Server : Due to server side rendering, it becomes costly and
-resource intensive, the server has to bear the full burden of rendering contents for users.

2) Slower page rendering : The Server side rendering is ideal for static HTML site
generation, but for complex applications it may result in slower page rendering.

Difference between Server-Side Rendering(SSR) and Client-Side Rendering(CSR) :


• In server side rendering, the HTML contents are generated on the server on the other
hand in client side rendering, the HTML contents are generated on the client side along
with Javascript.
The SSR sends the pre-rendered HTML page to the client. While CSR sends the
minimal HTML page to the client.
SSR requires additional server-side configuration while CSR requires less server-side
configuration.
SSR is useful for improving the initial page load time and search engine optimization.
On the other hand CSR is suitable for applications with dynamic user interfaces that
require frequent updates without refreshing the page.

Review Questions
What is server side rendering? Explain.
2 Give the adhvantages and disacdantages of serverside rendering
3 What is the diference betveen server side rendering and client side rendering.

TECHNICAL PUBLICATIONS- an up-thust for knowledge


Full Stack Web Development 5-38 React

5.11 Two Marks Questions with Answers


0.1 What is MERN stack ?
Ans. : MERN stack is a collection of four technologies that are used to develop full stack web
applications. MERN stack comprises of four technologies namely,
M stands for MongoDB which is used for preparing database.
E stands for Express mainly used for developing Node. js web framework.
R stands for React mainly used for developing client side JavaSeript framework.
N stands for Node.js which is an open source, cross - platform, JavaScript run - time
environnent that executes JavaScript code outside of a browser.
Q.2 What is ReactJS ?
Ans. ReactJS is an open source, component - based front end JavaScript library maintained by
:

Facebook.
This library is responsible only for the view layer of the application. That means this
JavaScript is for building user interfaces.
Q.3 What are functional components in ReactJS ?
Ans. : Functional components are simple JavaScript functions. The functional components
return the JSX(JavaScript XML)code to render the DOM tree. Following code
fragment shows
the functional comnponent
function Welcome(props) {
return <h1>Welcome {props.name)</h1>;

Altematively the functional component can be created using arrOw function as


follows
const Welcome = (props) =>{
retum <h1>Welcome {props.namne)</h1>;

Q.4 How to define class components in ReactJs ?


Ans. : To define the class component we have to first create a class and extend
React.Component class.
Class components are ES6 classes that return JSX. Below, is a
class component which is
similar to Welcome function(as given in Functional component) :
class Welcome extends React.Comnponent {
render() {
retum <h1>Welcome, (thís.props.name)</b1>;

TECHNICAL PUBLICATIONS-an
up-hrust for knowledge
Full Stack Web Development 5-39 React

Q.5 What is the' use of setState() function in ReactJS?


Ans. : The setState() is used to change the value of the state object. State can be updated in
response to event handlers, server responses, or prop changes.
This is done using the setState) method. The setState) method enqueues all of the updates
made to the component state and instructs React to re-render the component and its children with
the updated state.
Q,6 What is modularization ?
Ans. : Modularization is a technique which helps in code organization by splitting the code into
smaller parts. The modular architecture involves breaking down a program into subprograms
called modules.
Q.7 What is Webpack ?

Ans. Webpack in react is a JavaScript module bundler that is commonly used with React to
:

bundle and manage dependencies. The webpack takes all the necessary JavaScript fles, CSS
fles combine them into a single bundle that can be loaded by the browser.
Q.8 What is Babel ?
Ans. Babel is a JavaScript compiler that converts modern JavaScript code into the version
:

which is compatible with all the browsers. Babel transpiles modern JavaScript for use in React
Components. The transpiler is a tool used to convert source code into another source code of
same level.

The main reason we need babel in modularization is that it gives us the privilege to make use
of the latest things JavaScript has to offer without worrying about whether it will work in the
browser or not.
Q.9 What is React Router
a web
Ans. ReactJS router is a single page application. The single page application is
:

application that interacts with the user by dynamically rewriting the current page, rather than
a
loading entire new pages from the server. When a user types specific URL into the browser
and if this URL path matches any 'route' inside the router file, the
user will be redirected to that

particular route.
Q.10 List and explain the packages that are used in ReactJS routing
:
Ans.
1, react-router : It provides core routing components and functions for the React Router
application.
2. React-router-dom : This package enables the user to implement dynamic routing in a web
app.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Full Stack Web Development 5-40 React

Q,11 What is Server side Rendering (SSR) ?


Ans. :
Server Side Rendering (SSR) is a technique in which the HTML contents of React
application are displayed on the server side before sending it to client. With SSR the initial page
load is faster and it improves the search engine optimization.
In server side rendering technique the HTML page is created at the server side with all the
necessary contents of the site and then it is sent back to the user. The user willget fully rendered
HTML page that contains all the necessary information without having to wait for JavaScript
or CSS file to load.

TECHNICAL PUBLICATIONS- an up-thrust


for knowledge
SOLVED MODEL QUESTION PAPER
.
[As Per New Syllabus]
Full Stack Web Development
Semester - V (IT)

Time:Three Hours] [Maximum Marks: 100


Answer ALL Questions
PART A - (10 x 2 = 20 Marks)

Q.1 What is web development framework ? (Refer Two Marks Q.1 of Chapter - 1)

Q.2 What is fullstack ? (Refer Two Marks Q.10 of Chapter - 1)

Q.3 What is Nodejs ? Give its uses. (Refer Two Marks Q.1 of Chapter - 2)
Q.4 Explain the use of
ClientRequestobject. (Refer Two Marks Q.12 of Chapter - 2)

Q.5 What is NoSQL ? (Refer Two Marks Q.1 of Chapter - 3)

Q.6 Explain the createUser command in MongoDB.


(Refer Two Marks Q.5 of Chapter - 3)
Q.7 What is express. Enlist the features. (Refer Two Marks Q.1 of Chapter - 4)
Q.8 What is the use of ngModule in angular ? (Refer Two Marks Q.10 of Chapter - 4)

Q.9 What are functional components in ReacJS ? (Refer Two Marks Q.3of Chapter - 5)

Q.10 What is react router ? (Refer Two Marks Q.9 of Chapter - 5)


PART B - (5x 13 = 65 Marks)
Q.11 a).
i) Explain the full stack web development framework in detail with suitable block
diagram. (Refer section 1.7) [13]
OR
b) i) Explain MVCarchitecture. Also enlist the features
of
MVC architecture.

(Refer section 1.6) [6]

) What are the components of basic web development framework? Explain each.
(Refer section 1.1)
Q.12 a) i) What is Node Package Manager(NP M).
Also explain the command line options
of npm. (Refer section 2.4)

i) What is stream ? Eyplain how to perform read and write operations in Nodejs
using stream. (Refer section 2.10.2) [6]

(M- 1)
Full Stack Web Development M-2 Solved Model Question Paper

OR
b) i) How event listener is handled in Node.js. Explain it with suitable example code.
(Refer section 2.7) [7]

i) Explain any two built-in modules in Node,js. (Refer section 2.4.3) |6]
Q.13 a) ) Elaborate the steps sed for comecting the MongoDB with Node,js
(Refer section 3.8) [5]

i) Explain with suitable exanples, CRUD operations in MongoDB.


(Refer section 3.7) [8]

OR
b) i) How tocreate an inder and find the index in MongoDB ? Explain it with suitable
example. (Refer section 3.11.1) [5]

ii) Explain the i) MongoDBClient object and i)db object with methods
associated with it. (Refer section 3.9) [8]
Q.14 a) ) Explain the implementation of routing techmique in express with example.
(Refer section 4.2) [8]

i) Write a simple application in TypeScript demonstrating the interface.


(Refer section 4.7)
OR
b) ) Explain with suitable block diagram, the angular architecture.
(Refer section 4.14)
ij) Write a
code in TypeScript to implement the simple arithmetic calculator
application. Make use of inteface. (Refer example 4.7.1) [8]
Q.15 a) i) Explain the class components in ReactJS. (Refer section 5.3) [7]
ii) What is react state ? Explain it with example code. What is the difference
between props and state. (Refer section 5.6) [6]
OR
b) i) Explain the concept of modularization and web pack in React.js.
(Refer section 5.8)
|13]
PART C-(1 x 15=15 Marks)
Q.16 a) Write an application in ode.js demonstrating the
ClientRequest and
ServerResponse object with necessary illustrations. (Refer
section 2.11) [15]
OR
b) Create a simple student database in MongoDB and display
all the records in sorted
manier. (Refer section 3.10)
|15]

TECHNICAL PUBLICATIONS - an up-thrust


for knowledae
9l7 89355llgs3950|
Made in India
For Semester-V (IT)...

1. Computer Networks (vs. Bogad, I. A. Dhotre)

2. Full Stack Web Development (4. A. Puntambekar)

3. Embedded Systems and loT (.A. Dhotre, A. P. Godse)

4. Distributed Computing .A. Dhotre)

You might also like