0% found this document useful (0 votes)
23 views88 pages

13 - Marks - Full Stack Web Development

The document outlines the curriculum for a Full Stack Web Development course at V.S.B Engineering College, focusing on the basics of web development frameworks, including components like users, browsers, web servers, and backend services. It explains the roles of HTTP request types (GET, POST, AJAX), the significance of CSS in rendering webpages, and the Model-View-Controller (MVC) architecture. Additionally, it discusses the features and benefits of MVC frameworks in structuring web applications.
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)
23 views88 pages

13 - Marks - Full Stack Web Development

The document outlines the curriculum for a Full Stack Web Development course at V.S.B Engineering College, focusing on the basics of web development frameworks, including components like users, browsers, web servers, and backend services. It explains the roles of HTTP request types (GET, POST, AJAX), the significance of CSS in rendering webpages, and the Model-View-Controller (MVC) architecture. Additionally, it discusses the features and benefits of MVC frameworks in structuring web applications.
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/ 88

V.S.

B ENGINEERING COLLEGE, KARUR


(An Autonomous Institution)
Department of Information Technology
Academic Year 2023-2024 (ODD Semester)
IT3501 - FULL STACK WEB DEVELOPMENT
PART – B & C
UNIT - I : BASICS OF FULL STACK
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

1. Explain the basic components of a web framework and their roles in a web
application. (Nov/Dec 2020) [UN]
A web framework is a collection of software libraries and tools that help
developers build web applications. The main components of a web framework are
the user, browser, web server, and backend services.
 The user: The user is the person who interacts with the web application. The
user's actions, such as clicking on a link or submitting a form, are sent to the
browser.
 The browser: The browser is the software that the user uses to view web pages.
The browser interprets the HTML, CSS, and JavaScript code that makes up a web
page and displays it to the user.
 The web server: The web server is the software that hosts the web application.
The web server receives requests from the browser and sends back the
corresponding web pages.
 Backend services: Backend services are the software that provides the
functionality for the web application. Backend services can be implemented using
a variety of technologies, such as Node.js, Java, or Python.

2. Explain web development framework with suitable block diagram. Also explain
the components of it. [UN]
The User:
The user is the individual who interacts with the web application through their
browser. They perform actions like clicking on links, filling out forms, or interacting
1
with various elements presented on the web page.

The Browser:
The browser is the software used by the user to access and view web pages.
It interprets the HTML, CSS, and JavaScript code comprising the web page and
renders it in a visually understandable format for the user.
 Browser to webserver communication
o GET:
 GET is an HTTP method used to retrieve data from a specified
resource.
 It is a simple and lightweight request where data is appended in
the URL's query parameters.
 Commonly used to request data from the server, and it is
considered safe, idempotent, and cacheable.
 For example, when you enter a URL in the browser, it usually
sends a GET request to retrieve the web page.
o POST:
 POST is an HTTP method used to submit data to be processed
to a specified resource.
 It sends data in the request body, making it more secure and
suitable for sending sensitive or large amounts of data.
 Commonly used to submit forms, upload files, or perform
operations that modify the server's state.
 Unlike GET, POST requests are not cacheable, and they are not
guaranteed to be idempotent.
o AJAX (Asynchronous JavaScript and XML):
 AJAX is a web development technique that allows web pages to
interact with the server asynchronously without requiring a full
page reload.
 It enables seamless and dynamic updates on web pages,
improving user experience and reducing bandwidth usage.
 AJAX uses JavaScript to make asynchronous requests to the
server, and it can handle various HTTP methods like GET, POST,
PUT, DELETE, etc.
 It is commonly used to fetch data, update content, and submit
data in the background without interrupting the user's
interaction with the page.

The Web Server:


The web server acts as the hosting
software for the web application. It receives
requests from the user's browser, processes
those requests, and sends back the relevant
web pages or data in response.
 Apache
Apache, also known as Apache
HTTP Server, is a widely-used, open-
source web server software developed
and maintained by the Apache
2
Software Foundation. It is one of the most popular web servers globally and is
compatible with various operating systems, including Unix, Linux, Windows,
and macOS. Apache's primary function is to serve static and dynamic web
content to clients (browsers) over the internet using various protocols like
HTTP and HTTPS. It supports a wide range of modules, making it highly
extensible and capable of handling different web applications and
configurations.
 IIS
IIS, short for Internet Information Services, is a web server software
developed by Microsoft for Windows Server operating systems. It is a part of
the Windows Server family and is used to host websites, web applications,
and other web-related services on Windows-based servers. IIS supports
various protocols, including HTTP, HTTPS, FTP, SMTP, and more. It integrates
well with other Microsoft technologies and provides a user-friendly
management interface for configuration and administration. IIS is commonly
used in enterprise environments and is known for its performance, security
features, and seamless integration with Microsoft's ecosystem.

Backend Services:
Backend services are software components responsible for providing the core
functionality of the web application. They can be developed using various
technologies like Node.js, Java, Python, etc. These services handle the processing of
data, business logic, and respond to requests from the web server to serve dynamic
content to the user's browser.

3. Describe the three main types of requests that a browser can make to a
webserver, and provide examples of when each type is typically used. [UN]
The three main types of requests that a browser can make to a webserver are:
 GET: The GET request is used to retrieve data from the server. It is typically used
when requesting resources such as HTML files, images, or JSON data. For
example, when a user visits a website, their browser sends a GET request to fetch
the HTML file that represents the webpage.
 POST: POST requests are used when sending data to the server. It is commonly
used for actions like submitting a web form or adding an item to a shopping cart.
For instance, when a user fills out a contact form on a website and clicks the
submit button, their browser sends a POST request containing the form data to
the server.
 AJAX: AJAX requests are asynchronous requests initiated by JavaScript running
in the browser. They can be either GET or POST requests and are used to fetch
data from the server without requiring a full page reload. AJAX requests are often
used to update parts of a webpage dynamically. For example, when a user clicks
a "Load More" button on a social media feed, an AJAX request can be sent to
retrieve additional posts from the server.

4. Detail the role of CSS files in the rendering of a webpage by a browser, and
explain what they define. (Nov/Dec 2019) [UN]
CSS files play a crucial role in the rendering of a webpage by a browser. They
define the styles and visual presentation of each element on the page. Here's a more
detailed explanation:
3
CSS (Cascading Style Sheets) files are used to define the appearance of
HTML elements. They specify how elements should be styled, including properties
such as font, color, borders, spacing, and positioning. When a browser receives an
HTML document, it parses the CSS files associated with that document and applies
the specified styles to the corresponding elements.
CSS files use selectors to target specific elements or groups of elements on a
webpage. Selectors can target elements based on their HTML tag names, classes,
IDs, attributes, or their position within the document structure. By applying styles to
specific selectors, web designers can control the visual presentation of individual
elements or define consistent styles for groups of elements.
The separation of CSS from HTML allows for the separation of concerns in
web development. It enables web designers to focus on the visual design and layout
independently from the structure and content of the webpage. CSS provides a
powerful and flexible way to customize the look and feel of a webpage, making it an
essential component in the rendering process of a browser.

5. Examine the role of different types in the process of rendering a webpage in a


browser. [AN]
When rendering a webpage, the browser relies on various types of data to
build the final user view and define the webpage's behavior. Here's an explanation of
the role of each type of data:
 HTML files: These files define the structure of the webpage, creating a tree-like
structure known as the Document Object Model (DOM). The DOM represents the
hierarchy and relationships between elements like headings, paragraphs, and
images, forming the foundation of the webpage.
 CSS files: Cascading Style Sheets (CSS) files are used to style the elements on
the page. They define visual properties such as fonts, colors, spacing, and
positioning, ensuring a consistent and visually appealing look for the webpage.
 Client-side scripts: Usually written in JavaScript, these scripts add interactivity
and additional functionality to the webpage. They can manipulate the DOM
dynamically, allowing elements to change in response to user actions. Client-side
scripts enable features like form validation, dynamic content updates, and
communication with the webserver.
 Media files: Media files, such as images, videos, and audio, enrich the webpage
with multimedia content. They enhance the visual and interactive experience for
users, displaying images, playing videos, or presenting audio content directly
within the webpage.
 HTTP headers: These are important instructions that the browser and webserver
exchange during the loading process. HTTP headers contain essential
information, such as the type of data requested and the expected data type to be
returned. They also handle functionalities like session management and caching
to optimize webpage performance.

6. Classify the role of a webserver in handling requests from browsers, including


the handling of different types of requests and the use of server-side scripts.
(Nov/Dec 2021) [UN]
A webserver plays a crucial role in handling requests from browsers. Here's
an explanation of its role in handling different types of requests and the use of server
-side scripts:
4
 Handling Requests: The webserver's primary focus is to handle requests initiated
by browsers. The browser may make different types of requests, such as
requesting a document (GET request), submitting data to be processed (POST
request), or making AJAX requests to fetch data. The webserver uses the HTTP
headers and the URL provided by the browser to determine the action to be taken.
 Serving Static Files: Out-of-the-box webservers like Apache and IIS are designed
to serve static files, such as HTML, CSS, and media files. These files are directly
sent to the browser upon request without any server-side processing. The
webserver's role here is to locate and serve the requested static file to the
browser.
 Extending with Server-Side Scripts: To handle requests that involve modifying
server data or interacting with backend services, the webserver needs to be
extended with server-side scripts. Server-side scripts are programs that can be
executed by the webserver to perform the tasks requested by the browser. These
scripts can be written in various programming languages like PHP, Python, C, C++,
C#, Java, and more.
 Wiring Server-Side Scripts: Webservers like Apache and IIS provide mechanisms
to include server-side scripts and map them to specific URL locations requested
by the browser. This requires configuration to enable different scripting
languages and establish a routing mechanism where the webserver can direct
the appropriate request to the corresponding script.
 Generating Responses: Server-side scripts can generate the response directly by
executing their code or by connecting with other backend servers, such as
databases, to obtain necessary information. They then use this information to
construct and send the appropriate response back to the browser. Server-side
scripts enable dynamic content generation and data processing on the server-
side before the response is sent.

7. Explain the Model-View-Controller (MVC) architecture, including its features and


components, and describe how it works using an example. [UN]
The Model-View-Controller (MVC) architecture is a design pattern that
separates an application into three main components: Model, View, and Controller.
Here's an explanation of the MVC architecture, its features, components, and an
example of how it works:

Features of MVC:
 Clear separation of concerns: MVC provides a clear separation of business logic,
UI logic, and input logic. Each component has a specific role and responsibility,
making the application easier to understand and maintain.
 Control over HTML and URLs: MVC architecture allows developers to have full
control over the HTML output and URLs, enabling them to design a structured
and organized web application architecture.
 Powerful URL mapping: MVC offers a powerful URL-mapping component, which
allows developers to build applications with comprehensible and searchable
URLs, improving the overall user experience.

Components of MVC:

5
Controller: It connects the View
and Model, handles requests,
processes business logic, and
manipulates data. It instructs the
Model on actions and coordinates
with the View to show the final
output.
Model: It manages data-related
tasks, business logic, and data
storage/retrieval. It interacts with
databases, validates data, and
responds to requests from the
Controller.
View: Responsible for the user interface (UI) logic, it creates the UI presented to the
user. It receives data from the Model through the Controller and focuses on visually
appealing and user-friendly data presentation.

Working of MVC with an example:


Let's consider an example where a user requests a list of students studying in
a class. Here's how the MVC architecture would handle this scenario:
 The user sends a request to
the server to get a list of
students studying in a class.
 The server routes the request
to the appropriate Controller
that handles student-related
operations.
 The Controller receives the
request and processes it by
invoking the corresponding
methods in the Model
component.
 The Model component,
responsible for managing student-related data and operations, interacts with the
database to retrieve the list of students studying in the requested class.
 The Model returns the list of students to the Controller.
 The Controller then interacts with the appropriate View component and passes
the list of students to it.
 The View component uses the received data to generate the UI representation of
the list of students. It may apply formatting, styling, and layout to present the
information effectively.
 The View sends the generated UI output back to the user's browser, which can
then be displayed on the user's screen.

By following the MVC architecture, the application adheres to design principles


such as dividing and conquering complex tasks, increasing cohesion within
components, reducing coupling between components, increasing code reuse, and
designing for flexibility. This modular and organized structure makes the application
more maintainable, scalable, and easier to modify or extend in the future.
6
8. Enable the features of MVC framework. [UN]
The MVC (Model-View-Controller) framework is a software architectural
pattern used in web development to structure and organize code. It separates the
application's concerns into three interconnected components: Model, View, and
Controller. Each component has its own role and responsibilities, offering several
benefits:
Model:
 Represents the application's data and business logic.
 Manages the data storage, retrieval, and manipulation.
 Provides an abstraction layer over the database or data sources.
 Allows multiple views to access the same data without duplication.
 Enhances code reusability and maintainability by decoupling data-related
operations.

View:
 Represents the user interface (UI) and presentation layer.
 Displays data from the model to the user in a human-readable format.
 Separates the presentation logic from the business logic.
 Supports different views for the same data, allowing multiple UIs for diverse
devices (e.g., web browsers, mobile apps).
 Enhances user experience by providing a clean and well-organized UI.

Controller:
 Handles user interactions and acts as an intermediary between the model and
the view.
 Receives user input and initiates corresponding actions in the model and view.
 Updates the model based on user input and external events.
 Updates the view based on changes in the model.
 Promotes code modularity and testability by keeping UI-related logic separate
from the business logic.

Key Features and Benefits of MVC Frameworks:


 Modularity: MVC promotes the division of application components, allowing
developers to work on different parts of the application simultaneously,
enhancing collaboration and maintainability.
 Reusability: Code reusability is facilitated by the separation of concerns,
making it easier to reuse models, views, and controllers across different parts
of the application or even in other projects.
 Scalability: MVC's clear separation of components facilitates scalability, as
individual components can be optimized and scaled independently to handle
increasing loads.
 Testability: Each component's separation allows for easier unit testing of
models, views, and controllers, leading to more robust and reliable code.
 Enhanced Code Maintainability: With clear boundaries and a well-defined
structure, MVC makes code maintenance more straightforward and less error-
prone.
 Rapid Development: By dividing responsibilities, developers can work in
7
parallel, accelerating the development process.
 Flexibility: MVC allows developers to change or update one component
without affecting the others, making it easier to adapt to changing
requirements.
 Support for Front-end and Back-end Developers: MVC enables front-end
developers to focus on the view and UI, while back-end developers can
concentrate on the model and business logic.
 SEO-Friendly URLs: By implementing clean URLs through routing, MVC
frameworks can enhance SEO (Search Engine Optimization) for web
applications.
 Consistent Code Structure: MVC frameworks often follow a standardized
pattern, leading to consistent and organized codebases, even in large projects
with multiple developers.

9. Discuss the role of Express in the Node.js-to-Angular stack, including its features
and functionalities. [UN]
Express is a module in the Node.js-to-Angular stack that serves as the
webserver component. It extends Node.js to provide essential features for handling
web requests and makes it easy to configure, implement, and control web servers.
Here's an explanation of Express's role and its key features:

Role in the Node.js-to-Angular Stack:


Express acts as the webserver component in the Node.js-to-Angular stack. It
integrates with Node.js to handle incoming HTTP requests and serve appropriate
responses. Express enables the creation of robust and scalable web applications by
providing a set of tools and functionalities specifically designed for web server
development.

Features and Functionalities of Express:


 Route Management: Express makes it easy to define URL endpoints and specify
what actions to perform when users access those URLs. This helps developers
implement different functionalities for different routes.
 Error Handling: Express comes with built-in error handling, taking care of
common errors like documents not found. It also allows developers to create
custom error handlers to deal with application-specific errors, ensuring a smooth
user experience.
 Integration with Reverse Proxy: Express can be smoothly integrated into existing
systems that use a reverse proxy (like Nginx or Varnish). This allows the Express
server to work seamlessly within a secured infrastructure, combining the
advantages of both Express and the reverse proxy system.
 Cookie Management: Express simplifies the handling of HTTP cookies.
Developers can easily set and read cookies, which is useful for tasks like cookie-
based authentication and session management.
 Session and Cache Management: Express provides built-in support for managing
user sessions, allowing developers to store and retrieve session-related data.
Additionally, it offers mechanisms for efficient cache management, improving the
performance of web applications.

8
10. Elaborate the benefits of using Angular for web development. [UN]
Angular offers benefits such as powerful data binding, extensibility, enforced
clean code practices, code reusability, strong support from Google, and compatibility
with existing codebases.
Explanation:
Angular provides several advantages for web development:
 Data Binding: Angular simplifies data binding by efficiently connecting data to
HTML elements. This ensures seamless synchronization between data and the
user interface without manual DOM manipulation.
 Extensibility: Angular's architecture allows developers to customize and extend
various aspects of the framework to meet specific project needs. This flexibility
enables tailoring Angular for different requirements.
 Clean Code: Angular enforces clean coding practices, enhancing code readability
and maintainability. It encourages developers to follow best practices and create
organized code structures.
 Code Reusability: Through extensibility and clean coding, Angular promotes code
reusability. Developers can create modular components and services for easy
integration into different parts of an application.
 Support: Being backed by Google, Angular receives strong support and
continuous investment. Regular updates, bug fixes, and extensive documentation
are available, ensuring a reliable and well-supported framework.
 Compatibility: Angular is based on TypeScript, which enhances JavaScript with
static typing and advanced features. This compatibility allows for seamless
integration with existing environments and facilitates code reuse within Angular's
structure.

11. Summarize the advantages of using Node.js for web development. [UN]
Node.js offers advantages such as JavaScript end-to-end development, event-
driven scalability, extensibility through a vibrant development community, and quick
setup and development time.
Explanation:
Node.js provides several benefits for web development:
 JavaScript end-to-end: Node.js allows developers to write both server-side and
client-side scripts in JavaScript. This eliminates the need to switch between
different programming languages and enables seamless sharing of code and
logic between the client and server. It promotes a unified language across the
entire development stack, making it easier for developers to collaborate and
maintain consistency.
 Event-driven scalability: Node.js adopts an event-driven model for handling web
requests. Rather than relying on multiple threads, requests are processed on the
same thread using an event-driven approach. This enables Node.js webservers to
handle a large number of concurrent connections efficiently, resulting in
improved scalability and performance. This approach is particularly
advantageous for applications with high levels of concurrent I/O operations.
 Extensibility: Node.js has a thriving development community that actively
contributes to the ecosystem. This results in a vast collection of modules and
libraries that extend Node.js functionality. These modules can be easily installed

9
and incorporated into Node.js projects, allowing developers to enhance their
applications with new features and capabilities quickly.
 Time-efficient: Node.js offers a straightforward and quick setup process.
Installing Node.js and setting up a basic web server can be accomplished within
minutes. This rapid development setup allows developers to start coding and
iterating on their projects swiftly, leading to faster development cycles and
reduced time to market.

12. Outline the advantages of using MongoDB with Node.js for web development.
[UN]
MongoDB offers advantages such as document-oriented data storage, high
performance, high availability through replication, scalability, and immunity to SQL
injection.
Explanation:
When using MongoDB with Node.js for web development, there are several benefits:
 Document Orientation: MongoDB's document-oriented data storage aligns
well with the format commonly used in both server-side and client-side scripts.
The data is stored as JSON-like documents, eliminating the need for data
transformation between rows and objects. This simplifies the development
process and reduces data transfer overhead.
 High Performance: MongoDB is known for its high performance. With the
increasing demand for websites and heavy traffic, having a backend that can
efficiently handle large amounts of data and requests is crucial. MongoDB's
optimized architecture and indexing capabilities contribute to its high-
performance characteristics.
 High Availability: MongoDB offers a replication model that ensures high
availability. Replication enables data to be automatically synchronized across
multiple servers, providing fault tolerance and reducing the risk of downtime.
This feature is important for maintaining a reliable and responsive web
application.
 Scalability: MongoDB's structure makes horizontal scalability easy to achieve.
By distributing data across multiple servers, MongoDB can handle increased
loads and accommodate growing user bases without sacrificing performance.
This scalability capability is vital for web applications that anticipate future
growth.
 No SQL Injection: MongoDB's document-oriented approach eliminates the risk
of SQL injection attacks. Since objects are stored as objects, there is no need
to construct SQL strings dynamically based on user input. This significantly
enhances the security of the application and protects against common
injection vulnerabilities.

13. Examine the key features and benefits of using React for web development.
[AN]
React offers key features such as declarative views, component-based
architecture, elimination of templates, and isomorphic capability, resulting in
consistent and maintainable code, reusable components, enhanced developer
productivity, and improved performance.
Explanation:
React provides several key features and benefits for web development:
10
 Declarative Views: React's declarative nature allows developers to focus on
describing how the view should look based on the data, rather than manually
manipulating the DOM. This approach makes views more consistent,
predictable, and easier to maintain, as the framework handles the updates
and transitions automatically.
 Component-Based Architecture: React encourages a modular and reusable
approach to building web applications. Developers can create self-contained
components that encapsulate both the state and view logic. This component-
based architecture simplifies the application structure, enhances code
reusability, and enables a more organized and maintainable codebase.
 No Templates: Unlike many web application frameworks that rely on
templates to generate repetitive HTML or DOM elements, React leverages
JavaScript to construct and manipulate the DOM elements. This allows
developers to use the full power of a programming language they are already
familiar with, enabling more flexibility and eliminating the need to learn a
separate templating language.
 Isomorphic Capability: React supports isomorphic or universal JavaScript
applications, where the same code can run on both the server and the
browser. This enables server-side rendering of React components, improving
initial page load times and providing a better user experience. The ability to
share code between the server and client simplifies development and
maintenance.

14. Explain the use of Node.js in full stack development. [UN]


Node.js is a powerful tool in full-stack development that serves as the
backend technology for building scalable and efficient web applications. It plays a
key role in the following aspects of full-stack development:
Backend Development:
Node.js allows developers to use JavaScript on the server-side, which makes
it easier for full-stack developers to work seamlessly across the entire application
stack. With Node.js, developers can handle server-side tasks such as data
processing, authentication, and interacting with databases.

Asynchronous Programming:
One of Node.js's defining features is its non-blocking, asynchronous I/O
model. This allows it to efficiently handle multiple concurrent connections and
requests without blocking the application's execution. Asynchronous programming
is particularly beneficial for real-time applications and systems that require high
scalability and responsiveness.
RESTful API Development:
Node.js is well-suited for creating RESTful APIs, which enable communication
between the frontend and backend components of a web application. With its
lightweight and straightforward architecture, Node.js can efficiently process API
requests and deliver data to the frontend.

Real-time Applications:
Node.js is an excellent choice for developing real-time applications that
require instant data updates and communication between users. Its event-driven
nature and WebSocket support allow for efficient bidirectional communication,
11
making it ideal for applications like chat systems, collaborative tools, and online
gaming platforms.

Package Management with npm:


Node.js comes with npm (Node Package Manager), a vast ecosystem of open
-source libraries and modules. Developers can leverage npm packages to add
functionalities and features to their applications easily, saving time and effort during
development.

Server-Side Rendering (SSR):


Node.js can be used for server-side rendering, where the server renders web
pages before sending them to the client. This approach improves initial page load
times and enhances search engine optimization (SEO) by making content more
accessible to search engines.

Microservices Architecture:
Node.js works well in a microservices architecture, where applications are
broken down into smaller, independent services. Each microservice can be
developed and deployed separately using Node.js, facilitating easier maintenance
and scalability.

Cross-platform Compatibility:
Node.js runs on multiple platforms, including Windows, macOS, and various
Linux distributions, making it a versatile choice for full-stack development that can
be deployed across diverse environments.

In summary, Node.js serves as the backbone of full-stack development,


enabling seamless integration between frontend and backend components. Its
asynchronous, event-driven nature, along with its extensive ecosystem of packages,
makes it an excellent choice for building modern, real-time, and scalable web
applications.

15. Explain the role of react in web framework. [UN]


React is a popular JavaScript library used in web development, and it plays a
vital role as a front-end framework. Its primary focus is on building user interfaces
(UIs) and handling the view layer of web applications. Here's an explanation of the
role of React in the web framework landscape:

Component-Based UI Development:
React is based on a component-based architecture, where UI elements are
encapsulated into reusable components. Each component represents a specific part
of the UI and can be composed and combined to build complex user interfaces. This
modularity and reusability make it easier to manage and maintain large codebases.

Virtual DOM:
React uses a Virtual DOM (Document Object Model) to efficiently update the
UI. It creates a lightweight in-memory representation of the actual DOM, allowing it to
perform efficient diffing between the current and previous states of the Virtual DOM.
This way, React can identify the minimum number of DOM manipulations required
12
and update only the necessary parts of the actual DOM, leading to better
performance and faster rendering.

Declarative Syntax:
React follows a declarative programming paradigm, where developers specify
what the UI should look like for a given state. This declarative approach simplifies UI
development, as developers don't need to manage low-level DOM manipulation;
instead, they define the desired UI state, and React takes care of updating the DOM
accordingly.

Reactive Updates:
React automatically handles UI updates when the underlying data (state)
changes. When the state of a component changes, React efficiently recalculates the
Virtual DOM and updates the actual DOM accordingly. This reactivity ensures that
the UI stays in sync with the data, reducing the need for manual DOM manipulation.

Component Lifecycle and Hooks:


React provides a set of lifecycle methods and more recently introduced hooks
(e.g., useEffect, useState) that allow developers to control and manage component
behavior during various phases of its existence. These features enable developers to
handle tasks like data fetching, subscriptions, and cleanup efficiently.

One-Way Data Flow:


React follows a one-way data flow, where data flows from parent components
to child components. This helps maintain a clear and predictable data flow
throughout the application, preventing unexpected side effects and making
debugging more manageable.

Rich Ecosystem:
React has a vast and active ecosystem with a wide range of libraries, tools,
and extensions. This includes state management libraries like Redux and MobX, UI
component libraries like Material-UI and Ant Design, and tools for testing and
debugging React applications.

Cross-platform Compatibility:
React can be used to build web applications for desktop and mobile devices
using technologies like React Native. This allows developers to share code and
components between different platforms, streamlining the development process and
reducing development efforts.

In summary, React's role as a front-end framework is to simplify and


streamline the process of building interactive and dynamic user interfaces. Its
component-based architecture, Virtual DOM, declarative syntax, and reactivity make
it a powerful tool for creating modern and efficient web applications.

==>X<==

UNIT - II : NODE JS
13
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 I/O - Implementing HTTP services in Node.js

1. Explain the development of Node.js, its key features, and its applications.
Additionally, provide an overview of the built-in modules that come with Node.js
and their purposes. [UN]
 Node.js was created in 2009 by Ryan Dahl to address concurrency issues in web
services.
 It is built on the V8 JavaScript engine, which was optimized for web traffic by
Google.
 Node.js offers a scalable server-side environment that facilitates the seamless
integration of client and server code.
 It enables developers to switch between client and server code and reuse code
across both environments.
 Node.js is favored for its scalability, ease of maintenance, and faster
development.
 Notable companies using Node.js include Yahoo!, LinkedIn, eBay, New York
Times, Dow Jones, and Microsoft.
 Node.js is commonly used as a web server due to its optimized code for handling
HTTP traffic.
 It also finds application in web services APIs (e.g., REST), real-time multiplayer
games, backend web services, web-based applications, and multiclient
communication (such as instant messaging).
 Node.js comes with various built-in modules:
o Assertion testing: Used for testing code functionality.
o Buffer: Facilitates interaction with TCP streams and file system operations.
o C/C++ add-ons: Enables the use of C or C++ code as Node.js modules.
o Child processes: Allows the creation of child processes for parallel
execution.
o Cluster: Supports the utilization of multicore systems.
o Command line options: Provides Node.js commands for terminal usage.
o Console: Offers a debugging console for developers.
o Crypto: Enables the creation of custom encryption.
o Debugger: Facilitates debugging of Node.js files.
o DNS: Allows connections to DNS servers.
o Errors: Helps handle errors in Node.js applications.
o Events: Enables the handling of asynchronous events.
o File system: Provides file input/output capabilities using synchronous and
asynchronous methods.
o Globals: Makes frequently used modules readily available without the need
for explicit inclusion.
o HTTP: Supports various HTTP features.
o HTTPS: Enables HTTP over the TLS/SSL protocol.
o Modules: Provides the module loading system for Node.js.
o Net: Allows the creation of servers and clients.
o OS: Provides access to the operating system on which Node.js is running.
o Path: Enables access to file and directory paths.
14
o Process: Provides information about and control over the current Node.js
process.
o Query strings: Allows parsing and formatting of URL queries.
o Readline: Facilitates reading from a data stream interface.
o REPL: Enables developers to create a command shell.
o Stream: Offers an API for building objects with the stream interface.
o String decoder: Provides an API for decoding buffer objects into strings.
o Timers: Allows the scheduling of functions to be called in the future.
o TLS/SSL: Implements TLS and SSL protocols.
o URL: Enables URL resolution and parsing.
o Utilities: Provides support for various apps and modules.
o V8: Exposes APIs specific to the Node.js version of the V8 engine.
o VM: Allows the execution and compilation of code using a V8 virtual
machine.
o ZLIB: Enables compression using Gzip and Deflate/Inflate algorithms.

2. How can you install Node.js, and what are the key components included in the
Node.js installation? Additionally, how can you verify the successful installation of
Node.js and the npm command? [UN]
 To install Node.js, download the installer from the official website and run it on
your PC.
 The installation includes the "node" executable, which starts the Node.js
JavaScript VM and allows execution of JavaScript files or direct code input from
the console.
 The "npm" command is used to manage Node.js packages.
 The "node_modules" folder contains installed Node.js packages acting as
libraries to extend Node.js capabilities.
 To verify the installation, open a console prompt and execute the "node"
command to start the Node.js VM. Then, use the "console.log()" function to
output "Hello World" and ensure it displays correctly. Exit the console using
Ctrl+C (Windows) or Cmd+C (Mac).
 The successful installation of the "npm" command can be verified by executing
the "npm version" command in the OS console, which should display the version
information.
 Various IDE options are available for Node.js development, such as Eclipse with
Node.js plugins, WebStorm IDE by IntelliJ, and Visual Studio Code (recommended
for TypeScript functionality). Alternatively, any text editor can be used for writing
Node.js web applications, as most of the code consists of .js, .json, .html, and
.css files.

3. Detail the usage and functionality of the Node Package Manager (npm). Describe
the process of searching for and installing Node Packaged Modules using npm.
[UN]
Introduction to npm
 npm is a command-line utility for managing Node Package Modules.
 It facilitates finding, installing, removing, and publishing Node packages.
 npm serves as the link between the Node Package Registry and the development
environment.
15
Using npm for Package Management
npm command-line options
 The "search" option helps find module packages in the repository.
o Example: npm search express
 The "install" option is used to install a package from the repository, a
package.json file, or a local location.
 Examples:
o npm install
o npm install express
o npm install [email protected]
o npm install ../tModule.tgz
 The "install -g" option installs a package globally.
o Example: npm install express -g
 The "remove" option is used to remove a module.
o Example: npm remove express
 The "pack" option packages a module defined by the package.json file into a .tgz
file.
o Example: npm pack
 The "view" option displays details of a specific module.
o Example: npm view express
 The "publish" option publishes a module defined by a package.json file to the
registry.
o Example: npm publish
 The "unpublish" option removes a previously published module from the registry.
o Example: npm unpublish myModule
 The "owner" option allows adding, removing, and listing owners of a package in
the repository.
 Examples:
o npm add bdayley myModule
o npm rm bdayley myModule
o npm ls myModule

Searching for Node Package Modules


 npm allows searching for modules directly from the command prompt using the
"npm search <search_string>" command.
o Example: npm search openssl
 The search results are displayed in the command prompt.

Installing Node Packaged Modules


 To use a Node module in an application, it must be installed where Node can find
it.
 The "npm install <module_name>" command is used to install a Node module.
o Example: npm install express
 The installed module is downloaded to the development environment and placed
in the node_modules folder.
 The output of the npm install command displays the dependency hierarchy
installed with the module.
16
 Each dependency module is listed with its version.
 Node.js handles dependency conflicts by placing separate copies of conflicting
modules in each module's folder.

4. Detail the process of creating a simple Node.js application, including creating a


Node Packaged Module, publishing it to the NPM registry. [UN]
Creating a Node.js Packaged Module
 Create a project folder for the module.
 Inside the folder, create a JavaScript file with the desired functionality.
 Export the necessary functions using the exports object.
 Create a package.json file with essential directives such as name, version, and
main.
 Optionally, create a README.md file with instructions.
 Use the npm pack command to generate a local package module (.tgz file).

Publishing a Node.js Packaged Module to the NPM Registry


 Create a public repository for the module, such as on GitHub.
 Create an account on https://npmjs.org/signup.
 Use the npm adduser command to add the user to the environment.
 Modify the package.json file to include repository information and keywords.
 Use the npm publish command to publish the module to the NPM registry.

5. Summarize the concept of scheduling work using Timer and nextTick


implementing.
Breaking Work into Chunks. [UN]
 Work should be divided into smaller chunks that can be executed as a series of
callbacks.
 This allows for non-blocking execution and efficient utilization of the event loop.

Scheduling Work on the Event Queue


 Call blocking I/O library functions: Use blocking I/O functions provided by Node.js
libraries that handle the work asynchronously.
 Add listeners to built-in events: Register listeners for events emitted by built-in
modules or libraries.
 Create custom event emitters and add listeners: Implement custom event
emitters and attach listeners to handle specific events.
 Use process.nextTick to schedule work on the next event loop cycle: This allows
scheduling work to be executed before I/O events in the next cycle.
 Use timers to schedule work after a specific amount of time or at periodic
intervals.

Using nextTick to Schedule Work


 process.nextTick(callback) schedules work to be run on the next cycle of the
event loop.
 Executed before I/O events, but can result in I/O event starvation.
 Limit the number of nextTick() events using process.maxTickDepth (default is
1000).

17
Implementing Timers
 Delaying Work with Timeouts
o Use timeout timers to delay work for a specific amount of time.
o setTimeout(callback, delayMilliseconds, [args]) is used to create a timeout
timer.
o Use clearTimeout(timeoutId) to cancel a timeout timer.
 Performing Periodic Work with Intervals
o Use interval timers to perform work at regular intervals.
o setInterval(callback, delayMilliseconds, [args]) is used to create an interval
timer.
o Use clearInterval(intervalId) to cancel an interval timer.
 Performing Immediate Work
o Immediate timers allow performing work as soon as I/O event callbacks
finish, before timeouts or intervals.
o Use setImmediate(callback, [args]) to create an immediate timer.
o Use clearImmediate(immediateId) to cancel an immediate timer.
 Dereferencing Timers from the Event Loop
o Use unref() to notify the event loop to not continue when a timer is the only
event left in the queue.
o Use ref() to re-reference a timer if you don't want the program to terminate
when it's the only event left.

Implementing Event Emitters and Listeners


 Adding Custom Events to Objects
o Events are emitted using an EventEmitter object from the events module.
o Use emit(eventName, [args]) to trigger an event.
 Adding Event Listeners to Objects
o Listeners are added using functions like addListener(eventName, callback)
or on(eventName, callback).
o Use once(eventName, callback) to listen to the event only once.
 Removing Listeners from Objects
o Use functions like listeners(eventName), setMaxListeners(n), and
removeListener(eventName, callback) to manage listeners.

6. Examine the concept of callbacks in Node.js. Provide a brief explanation of


passing additional parameters to callback functions with an example. [AP]
Implementing Callbacks in Node.js:
Callbacks play a crucial role in Node.js, allowing asynchronous and event-
driven programming. They provide a way to handle the completion of a non-blocking
operation or respond to an event. Here is a breakdown of implementing callbacks in
Node.js:

Overview of Callbacks:
 Callbacks are functions that are passed as arguments to other functions.
 They allow code to be executed once an asynchronous operation is complete or
an event is triggered.
 Callbacks facilitate non-blocking behavior, ensuring that the program continues
to execute without waiting for the operation to finish.
18
Passing Additional Parameters to Callbacks:
 Additional parameters can be passed to callback functions, enabling custom data
to be provided from the calling function.
 This allows flexibility in handling the callback and tailoring it to specific needs.
 The parameters can be passed when emitting an event or invoking the callback
function.

Example:
// Event emitter example
var events = require('events');
function CarShow() {
events.EventEmitter.call(this);
this.seeCar = function(make) {
this.emit('sawCar', make);
};
}
CarShow.prototype.__proto__ = events.EventEmitter.prototype;
var show = new CarShow();
function logCar(make) {
console.log("Saw a " + make);
}
function logColorCar(make, color) {
console.log("Saw a %s %s", color, make);
}
show.on("sawCar", logCar);
show.on("sawCar", function(make) {
var colors = ['red', 'blue', 'black'];
var color = colors[Math.floor(Math.random() * 3)];
logColorCar(make, color);
});
show.seeCar("Ferrari");
show.seeCar("Porsche");

Explanation:
 The example demonstrates passing parameters to callbacks using an event
emitter.
 The CarShow function inherits from events.EventEmitter to become an event
emitter.
 The seeCar method emits the 'sawCar' event with the make parameter.
 Two event handlers, logCar and an anonymous function, are registered to handle
the 'sawCar' event.
 logCar logs the car make, while the anonymous function selects a random color
and calls logColorCar with both the make and color parameters.
 By calling show.seeCar() multiple times with different car makes, the 'sawCar'
event is triggered, and the associated callbacks are executed.

7. Examine the concept of closure in callbacks. Provide a brief explanation of how

19
closure is implemented in callback functions with an example. [AP]
Implementing Closure in Callbacks:
Closure in JavaScript refers to the ability of a function to retain access to
variables from its parent function's scope, even after the parent function has finished
executing. When working with asynchronous callbacks, closure is necessary to
ensure that the callback can access the required variables from the parent function's
scope when it is executed.

Overview of Closure in Callbacks:


 Closure allows a function to remember and access variables from its lexical
scope, even when it is invoked outside of that scope.
 In the context of callbacks, closure ensures that the callback function can access
and use variables from the parent function, even after the parent function has
completed its execution.

Implementing Closure in Callbacks:


To implement closure in callback functions, the following steps are typically followed:
 Define the parent function that contains the variables and the callback function.
 Inside the parent function, define the callback function that requires access to
the variables from the parent scope.
 Use closure by either directly referencing the required variables within the
callback function or creating a closure wrapper function to encapsulate the
variables.

Example:
function logCar(logMsg, callback) {
process.nextTick(function() {
callback(logMsg);
});
}
var cars = ["Ferrari", "Porsche", "Bugatti"];
// Basic callback implementation without closure
for (var idx in cars) {
var message = "Saw a " + cars[idx];
logCar(message, function() {
console.log("Normal Callback: " + message);
});
}
// Callback implementation with closure
for (var idx in cars) {
var message = "Saw a " + cars[idx];
(function(msg) {
logCar(msg, function() {
console.log("Closure Callback: " + msg);
});
})(message);
}

Explanation:
20
 The example demonstrates two implementations of callbacks, one without
closure and one with closure.
 The logCar function takes a logMsg parameter and a callback function as
arguments.
 Inside logCar, the process.nextTick method is used to schedule the execution of
the callback function asynchronously.
 In the first loop, the callback function is defined without closure. The message
variable is overwritten in each iteration, and when the callback is executed, it
always displays the last value of message.
 In the second loop, a closure wrapper function is used. A self-invoking function
creates a new scope, and the message value is passed as an argument (msg).
This ensures that each callback retains its own copy of the message value,
resulting in the correct output.

8. Explain the concept of chaining callbacks in JavaScript. Provide a brief


explanation of how callbacks can be chained together to control the flow of
asynchronous operations, along with an example. [UN]
Chaining Callbacks:
Chaining callbacks refers to the practice of calling a callback function from
within another callback function, creating a sequence or chain of asynchronous
operations. This allows you to ensure the order of execution and control the flow of
asynchronous functions.

Overview of Chaining Callbacks:


 Chaining callbacks is a technique used in JavaScript to control the flow of
asynchronous operations and ensure the desired order of execution.
 By calling a callback function from within another callback function, you can
create a chain of asynchronous functions that execute one after the other.

Implementing Callback Chaining:


To implement callback chaining, the following steps are typically followed:
 Define the asynchronous function that takes a callback function as an argument.
 Inside the asynchronous function, perform the asynchronous operation.
 Upon completion of the operation, call the provided callback function, passing
any relevant data as arguments.
 In the callback function, handle the result or perform additional asynchronous
operations.
 Call another asynchronous function from within the callback function, if
necessary, to continue the chain.
 Repeat steps 3-5 as needed to create a sequence of asynchronous operations.
Example:
function logCar(car, callback) {
console.log("Saw a %s", car);
if (cars.length) {
process.nextTick(function() {
callback();
21
});
}
}
function logCars(cars) {
var car = cars.pop();
logCar(car, function() {
logCars(cars);
});
}
var cars = ["Ferrari", "Porsche", "Bugatti", "Lamborghini", "Aston Martin"];
logCars(cars);

Explanation:
 The example demonstrates how to chain callbacks to log a list of cars
sequentially.
 The logCar function is defined, which takes a car parameter and a callback
function as arguments.
 Inside logCar, it logs a message indicating that a car was seen.
 If there are still more cars in the cars array, it schedules the execution of the
callback function asynchronously using process.nextTick, effectively chaining the
callbacks.
 The logCars function is defined, which takes an array of cars as a parameter.
 It uses the pop method to retrieve and remove the last car from the array.
 The logCar function is called with the current car and a callback function that
recursively calls logCars with the updated array of cars until there are no more
cars left.
 Finally, the logCars function is called initially to start the callback chain.

9. Explain how Node.js supports working with JSON data. Provide a brief
explanation of converting JSON to JavaScript objects and vice versa, along with a
code example for each. (Nov/Dec 2018) (Apr/May 2021) (Nov/Dec 2021) [UN]
Working with JSON in Node.js:
JSON (JavaScript Object Notation) is a widely used data interchange format
in Node.js applications. Node.js provides built-in mechanisms for handling JSON
data, allowing developers to convert JSON strings to JavaScript objects and vice
versa.

Converting JSON to JavaScript Objects:


To convert a properly formatted JSON string to a JavaScript object, the
following syntax is used:
 var jsonObject = JSON.parse(jsonString);
 The JSON.parse() method is called with the JSON string (jsonString) as the
argument.
 It parses the JSON string and converts it into a corresponding JavaScript object
(jsonObject).

Example:
var accountStr = '{"name":"Jedi", "members":["Yoda","Obi Wan"], "number":34512,

22
"location":"A galaxy far, far away"}';
var accountObj = JSON.parse(accountStr);

console.log(accountObj.name);
console.log(accountObj.members);

Output:
Jedi
[ 'Yoda', 'Obi Wan' ]

 In the example, a JSON string (accountStr) represents an account with properties


such as name, members, number, and location.
 Using JSON.parse(), the JSON string is converted into a JavaScript object
(accountObj).
 The properties of the JavaScript object are accessed and logged to the console.

Converting JavaScript Objects to JSON:


To convert a JavaScript object to a properly formatted JSON string, the
following syntax is used:
 var jsonString = JSON.stringify(jsonObject);
 The JSON.stringify() method is called with the JavaScript object (jsonObject) as
the argument.
 It converts the JavaScript object into a properly formatted JSON string
(jsonString).
Example:
var accountObj = {
name: "Baggins",
number: 10645,
members: ["Frodo", "Bilbo"],
location: "Shire"
};
var accountStr = JSON.stringify(accountObj);

console.log(accountStr);

Output:
{"name":"Baggins","number":10645,"members":["Frodo","Bilbo"],"location":"Shire"}

 In the example, a JavaScript object (accountObj) represents an account with


properties such as name, number, members, and location.
 Using JSON.stringify(), the JavaScript object is converted into a properly
formatted JSON string (accountStr).
 The JSON string is logged to the console.

10. Explain the different operations performed on buffers in Node.js. Provide a brief
explanation of each operation along with relevant methods and examples. [UN]
Working with Buffers in Node.js:
Creating Buffers:

23
Creating buffers involves allocating memory and specifying their initial
contents. There are three methods for creating buffers in Node.js:
 new Buffer(sizeInBytes): Creates a buffer with a specified size in bytes.
 new Buffer(octetArray): Creates a buffer with initial contents provided as an array
of octets.
 new Buffer(string, [encoding]): Creates a buffer with initial contents provided as a
string, with an optional encoding specified.

Writing to Buffers:
Writing to buffers involves modifying the contents of a buffer. Buffer objects
have various methods for writing data:
 buffer.write(string, [offset], [length], [encoding]): Writes a specified number of
bytes from the string into the buffer starting at the offset index, using the
specified encoding.
 buffer[offset] = value: Replaces the data at the specified offset index with the
provided value.
 buffer.fill(value, [offset], [end]): Writes the specified value to every byte in the
buffer within the specified offset range.
 Various writeInt8, writeInt16LE, writeInt16BE, and other methods exist for writing
integers, unsigned integers, doubles, and floats of different sizes and endianness.

Reading from Buffers:


Reading from buffers involves retrieving and decoding data from a buffer.
Buffer objects have various methods for reading data:
 buffer.toString([encoding], [start], [end]): Converts a portion of the buffer to a
string using the specified encoding, start index, and end index.
 stringDecoder.write(buffer): Decodes and returns a string version of the buffer
using the specified encoding.
 buffer[offset]: Retrieves the octet value at the specified offset index.
 Various readInt8, readInt16LE, readInt16BE, and other methods exist for reading
integers, unsigned integers, doubles, and floats of different sizes and endianness.

Determining Buffer Length:


Determining the buffer length involves finding the number of bytes used by a
buffer. The length of a buffer can be determined using the .length property on the
Buffer object. However, when dealing with strings, Buffer.byteLength(string,
[encoding]) should be used to get the byte length instead of the character length.

Copying Buffers:
Copying buffers involves creating a new buffer with the contents of an
existing buffer. Buffers can be copied using the buffer.copy(targetBuffer,
[targetStart], [sourceStart], [sourceEnd]) method, which copies a portion of the
source buffer into the target buffer. Buffers can also be copied by directly indexing
the buffers, ensuring that both buffers use the same encoding when copying string
data.

Slicing Buffers:
Slicing buffers involves dividing a buffer into smaller sections. The

24
buffer.slice([start], [end]) method returns a new buffer that points to a specific range
of indexes in the original buffer. Changes made to a slice affect the original buffer,
and vice versa.

Concatenating Buffers:
Concatenating buffers involves combining multiple buffers into a single buffer.
The Buffer.concat(list, [totalLength]) method takes an array of Buffer objects as the
first parameter and returns a new buffer containing the concatenated data. The
optional totalLength parameter can be provided to specify the total length of the
concatenated buffer.

11. Illustrate the different types of streams in Node.js. Provide a brief overview of
each type of stream along with their methods and events. [UN]
Using the Stream Module to Stream Data in Node.js:
Readable Streams:
Readable streams allow reading data from a source into an application. They
are commonly used for sources like HTTP responses, file streams, and TCP sockets.
Methods:
read([size]): Read data from the stream, where size is an optional parameter
specifying the number of bytes to read.
Events:
data: Fired when data is available to be read from the stream.
end: Fired when the stream has reached the end, and no more data is available.
error: Fired when an error occurs during reading.
Writable Streams:
Writable streams enable writing data to a destination. They are commonly
used for destinations like HTTP requests, file streams, and TCP sockets.
Method:
write(chunk, [encoding], [callback]): Write data to the stream, where chunk is the
data to be written, encoding is an optional parameter specifying the character
encoding, and callback is an optional callback function called when the data has
been successfully written.
Events:
drain: Fired when the writable stream is no longer busy and can accept more data.
finish: Fired when all data has been written to the stream and it has been closed.
error: Fired when an error occurs during writing.

Duplex Streams:
 Duplex streams combine the functionality of readable and writable streams. They
are commonly used for sources and destinations that require both reading and
writing, such as TCP sockets.
 Duplex streams are created by inheriting from stream.Duplex and implementing
the _read(size) and _write(data, encoding, callback) methods.

Transform Streams:
 Transform streams modify data between the readable and writable ends. They
are useful for performing data transformations like compression or encryption.
 Transform streams are created by inheriting from stream.Transform and
implementing the _transform(chunk, encoding, callback) and _flush(callback)
25
methods.

Summary:
 Readable streams allow reading data from a source.
 Writable streams enable writing data to a destination.
 Duplex streams combine the functionality of readable and writable streams.
 Transform streams modify data between the readable and writable ends.

12. Elaborate the process of compressing and decompressing data using the Zlib
module in Node.js. [UN]
Compressing and Decompressing Data with Zlib in Node.js:
Compressing and Decompressing Buffers:
The Zlib module in Node.js provides helper functions for compressing and
decompressing data buffers. These functions follow a similar format:
function(buffer, callback), where function represents the compression or
decompression method, buffer is the buffer to be processed, and callback is the
function executed after the compression or decompression is complete.

Compression Methods:
 gzip/gunzip: Performs standard gzip compression.
 deflate/inflate: Utilizes the deflate compression algorithm based on Huffman
coding.
 deflateRaw/inflateRaw: Applies the deflate compression algorithm to a raw
buffer.

Syntax for Compressing a Buffer:


 gzip/gunzip: zlib.gzip(buffer, callback)
 deflate/inflate: zlib.deflate(buffer, callback)
 deflateRaw/inflateRaw: zlib.deflateRaw(buffer, callback)

Syntax for Decompressing a Buffer:


 gzip/gunzip: zlib.gunzip(buffer, callback)
 deflate/inflate: zlib.inflate(buffer, callback)
 deflateRaw/inflateRaw: zlib.inflateRaw(buffer, callback)

Compressing and Decompressing Streams:


Compressing and decompressing streams using Zlib in Node.js involves
utilizing the pipe() function to redirect data from one stream through the
compression or decompression object to another stream.

Syntax for Compressing a Readable Stream into a Writable Stream:


var gzip = zlib.createGzip();
readableStream.pipe(gzip).pipe(writableStream);

Syntax for Decompressing a Readable Stream of Compressed Data into a Writable


Stream:
var gunzip = zlib.createGunzip();
compressedStream.pipe(gunzip).pipe(uncompressedStream);
26
Summary:
 The Zlib module in Node.js offers convenient helper functions for compressing
and decompressing data buffers.
 Buffers can be compressed or decompressed using functions like zlib.gzip(),
zlib.gunzip(), zlib.deflate(), zlib.inflate(), zlib.deflateRaw(), and zlib.inflateRaw().
 Compressing and decompressing streams involves using the pipe() function to
direct data through compression or decompression objects.
 Compressing and decompressing data using Zlib in Node.js enables efficient
handling of large data sets in various applications.

13. Discuss the various HTTP objects in Node.js. [UN]


HTTP Objects in Node.js:
The http.ClientRequest Object:
The http.ClientRequest object is used to send an HTTP request from a client
to a server.
 Creating a ClientRequest Object with http.request():
o Syntax: const http = require('http');
o Method: const request = http.request(options, callback);
 Properties and Options of the ClientRequest Object:
o Properties: request.method, request.headers, request.path, etc.
o Options: method, headers, path, hostname, port, etc.
 Events and Methods provided by the ClientRequest Object:
o Events: request.on('response', callback), request.on('error', callback), etc.
o Methods: request.write(data), request.end(), etc.

The http.ServerResponse Object:


The http.ServerResponse object represents the response sent by an HTTP
server to a client.
 Creating a ServerResponse Object in an HTTP server:
o Syntax: http.createServer((request, response) => { ... });
 Writing Headers and Data to the Response using the ServerResponse Object:
o Syntax: response.writeHead(statusCode, headers);, response.write(data);,
response.end();
 Events and Methods available on the ServerResponse Object:
o Events: response.on('finish', callback), response.on('error', callback), etc.
o Methods: response.setHeader(name, value), response.write(chunk),
response.end(data), etc.

The http.IncomingMessage Object:


The http.IncomingMessage object represents the client request or server
response.
 Representing Client Requests and Server Responses:
o Syntax: http.createServer((request, response) => { ... });
 Reading Data from the IncomingMessage Object as a Readable Stream:
o Syntax: request.on('data', callback), request.on('end', callback), etc.
 Properties, Events, and Methods of the IncomingMessage Object:
o Properties: request.method, request.url, request.headers, etc.
27
o Events: request.on('data', callback), request.on('end', callback), etc.
o Methods: request.setEncoding(encoding), request.pause(),
request.resume(), etc.

The http.Server Object:


The http.Server object is used to implement an HTTP server.
 Implementing an HTTP server with the Server object:
o Syntax: const http = require('http');
o Method: const server = http.createServer(requestListener);
 Handling Events such as request, connection, close, etc.:
o Events: server.on('request', callback), server.on('connection', callback),
server.on('close', callback), etc.
 Starting the Server and Listening for Incoming Requests:
 Method: server.listen(port, hostname, backlog, callback)

Summary:
 HTTP objects in Node.js, such as http.ClientRequest, http.ServerResponse,
http.IncomingMessage, and http.Server, are essential for handling HTTP
communication.
 The http.ClientRequest object allows clients to send HTTP requests to servers.
 The http.ServerResponse object represents the response sent by an HTTP server.
 The http.IncomingMessage object represents client requests or server responses.
 The http.Server object enables the implementation of HTTP servers.
 These objects have properties, events, and methods that provide functionality for
handling and processing HTTP communication in Node.js applications.

14. Explain any four methods of console objects in node.js with suitable examples.

[UN]
In Node.js, the console object provides various methods to interact with the
console, allowing developers to log messages, debug their applications, and inspect
variables during development. Here are four commonly used methods of the console
object with suitable examples:

console.log()
 The console.log() method is used to log messages to the console.
 It accepts one or more arguments and prints them to the console.
const message = "Hello, Node.js!";
const number = 42;
const obj = { name: "John", age: 30 };

console.log("A simple message");


console.log("This is a number:", number);
console.log("An object:", obj);
console.log("A formatted message - Name: %s, Age: %d", obj.name,
obj.age);

console.error()
28
 The console.error() method is used to log error messages to the console.
 It is similar to console.log() but is typically used for reporting errors.
const fs = require("fs");

fs.readFile("non_existent_file.txt", "utf8", (err, data) => {


if (err) {
console.error("Error reading file:", err.message);
return;
}
console.log("File content:", data);
});

console.warn()
 The console.warn() method is used to log warning messages to the console.
 It is similar to console.log() but is typically used for non-critical warnings.
function divide(a, b) {
if (b === 0) {
console.warn("Division by zero is not allowed.");
return null;
}
return a / b;
}

const result = divide(10, 0); // Will log a warning

console.time() and console.timeEnd()


 console.time() and console.timeEnd() are used to measure the execution time
of a specific block of code.
 They can help identify performance bottlenecks in the application.
function timeConsumingOperation() {
console.time("time-consuming-operation");
// Simulate a time-consuming operation
for (let i = 0; i < 1000000; i++) {
// Some computation
}
console.timeEnd("time-consuming-operation");
}
timeConsumingOperation();

In this example, console.time() starts a timer labeled "time-consuming-


operation," and console.timeEnd() stops the timer and logs the time taken to execute
the time-consuming operation.

These console methods are valuable tools for developers during the
development phase as they provide valuable information, such as log messages,
errors, warnings, and execution times, which aid in debugging and improving the
performance of Node.js applications.

15. Explain the callbacks in node.js with suitable example. [UN]


29
In Node.js, callbacks are functions that are passed as arguments to other
functions and executed later, typically once an asynchronous operation is completed.
Callbacks are a fundamental concept in Node.js to handle asynchronous code and
ensure that operations occur in the correct sequence. Here's an example of using
callbacks in Node.js:
// Simulating an asynchronous operation that takes some time to complete
function fetchDataFromServer(callback) {
setTimeout(() => {
const data = { name: "John Doe", age: 30 };
callback(data); // Call the callback function with the fetched data
}, 2000); // Simulate a delay of 2 seconds
}

// Callback function to handle the fetched data


function processData(data) {
console.log("Received data:", data);
}

console.log("Start fetching data...");


fetchDataFromServer(processData);
console.log("Fetching data..."); // This line executes immediately

In this example, we have a function called fetchDataFromServer that


simulates an asynchronous operation using setTimeout. It takes a callback function
(callback) as an argument. After a delay of 2 seconds, it fetches some data and calls
the callback function, passing the fetched data as an argument.

We also have a callback function called processData, which logs the received
data to the console. This function is passed as an argument to fetchDataFromServer
when we call it.

When we run the code, we get the following output:


Start fetching data...
Fetching data...
Received data: { name: 'John Doe', age: 30 }

Here's how the code flow works with callbacks:


 We start by calling fetchDataFromServer(processData). The
fetchDataFromServer function initiates the asynchronous operation and sets
a timer for 2 seconds.
 While the asynchronous operation is ongoing, the code continues executing,
and console.log("Fetching data...") is executed immediately, without waiting
for the data to be fetched.
 After 2 seconds, the asynchronous operation completes, and the callback
function (processData) is called with the fetched data ({ name: 'John Doe', age:
30 }). The processData function logs the received data to the console.

30
This demonstrates how callbacks allow us to handle asynchronous operations in
Node.js, ensuring that code is executed in the correct order once the operation is
completed. Callbacks are a crucial part of Node.js and are widely used for I/O
operations, file handling, database queries, and more. However, as the codebase
grows, callbacks can lead to callback hell and code that is hard to read and maintain.
To address this issue, other patterns like Promises and async/await have been
introduced in modern JavaScript and Node.js.

==>X<==

UNIT - III : 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

1. Find the key considerations and strategies for optimizing data storage and
access in MongoDB. [UN]
Planning Your Data Model
 Before implementing a MongoDB database, it's important to understand your
data, how it will be stored, and how it will be accessed. Here are key questions to
consider:
 What are the main objects in your application?
 What is the relationship between different object types?
 How often will objects be added, deleted, or changed?
 How often will objects be accessed?
 How will objects be accessed (by ID, property values, etc.)?
 How will groups of objects be accessed?
These questions will help guide the structure of your collections and documents
in MongoDB, optimizing data storage and access.

Normalizing Data with Document References


 Minimizing Redundancy and Dependency
 Storing Subobjects Separately
 Advantages: Smaller Database Size, Easy Modification, Reduced Duplication
 Disadvantage: Additional Lookup Impacting Performance

Example:
 Users have a favorite store represented by a subobject (FavoriteStore).
 Instead of duplicating FavoriteStore data in each User object, it is stored as a
separate document in the FavoriteStores collection.
 Users reference the FavoriteStore document using an _id object property.

Denormalizing Data with Embedded Documents


 Embedding Subobjects Directly
 Suitable for One-to-One or Small, Static Subobjects
 Advantages: Faster Lookup, No Additional Lookups
 Downsides: Slower Insertion, Extra Disk Space for One-to-Many Relationships

31
Example:
 Users have home and work contact information represented by subobjects
(Home and Work).
 If the work contact information is shared by many users, it may be stored as a
separate document.
 If the work contact information is frequently or always queried together with the
User object, it should be embedded within the User document.

Using Capped Collections


 Capped collections have a fixed size and are suitable for objects with high rates
of insertion, retrieval, and deletion.
 Benefits of capped collections: preservation of insertion order, elimination of
indexing overhead, automatic removal of oldest documents.
 Restrictions of capped collections: no updates to larger sizes, inability to delete
documents (requires dropping the collection).

Understanding Atomic Write Operations


 Fixed Size for High Insertion, Retrieval, and Deletion Rates
 Benefits: Preservation of Insertion Order, Elimination of Indexing Overhead,
Automatic Removal of Oldest Documents
 Restrictions: No Updates to Larger Sizes, Requires Collection Drop for Deletion

Considering Document Growth


 Updates and Document Relocation
 Using Normalized Objects for Frequent Growth

Identifying Indexing, Sharding, and Replication Opportunities


 Improving Performance with Indexes
 Scaling with Sharding and Replication

Large Collections Versus Large Numbers of Collections


 Considering Design Impact on Performance
 Breaking up Larger Collections if Needed

Deciding on Data Life Cycles


 Defining Document Lifespan Based on Relevance
 Using Time-to-Live (TTL) Mechanism for Automatic Deletion

Considering Data Usability and Performance


 Striking a Balance between Functionality and Speed
 Scalability for Future Changes in Usability Requirements

2. What are the steps involved in installing and starting MongoDB on a specific
platform, and how can you access MongoDB from the shell client? [RE]
Installing MongoDB
 Visit the MongoDB website (http://docs.mongodb.org/manual/installation/) and
follow the instructions to download and install MongoDB for your specific
platform.
32
 Download and extract the MongoDB files.
 Add the <mongo_install_location>/bin directory to your system's PATH
environment variable.
 Create a data files directory: <mongo_data_location>/data/db.
 Start MongoDB by running the following command from the console prompt:
o mongod --dbpath <mongo_data_location>/data/db

Starting MongoDB
 To start the MongoDB database engine, execute the mongod (or mongod.exe on
Windows) executable located in the <mongo_install_location>/bin directory.
 You can pass various parameters to the mongod executable to control its
behavior. Some commonly used parameters include:
o --port <port>: Specifies the TCP port on which MongoDB listens for client
connections (default: 27017).
o --bind_ip <ip_address>: Specifies the IP address on which MongoDB binds
to and listens for connections (default: All Interfaces).
o --dbpath <path>: Specifies the directory for MongoDB to store its data.
 Here's an example of starting MongoDB with specified port and dbpath
parameters:
o mongod --port 28008 --dbpath <mongo_data_location>/data/db

Stopping MongoDB
 To stop the MongoDB database, you can use the MongoDB shell.
 Open the MongoDB shell by running the mongo command from the console
prompt.
 Switch to the admin database using the use admin command.
 Shutdown the database engine by running the db.shutdownServer() command.

Accessing MongoDB from the Shell Client


 After installing and starting MongoDB, you can access it through the MongoDB
shell.
 Launch the MongoDB shell by running the mongo command from the console
prompt.
 The MongoDB shell is an interactive shell that allows you to administer and
interact with MongoDB databases.
 You can perform tasks such as creating user accounts, databases, collections,
and querying the database contents.
 The shell is based on JavaScript, so many JavaScript syntax features are
available.
 Changes made in the shell directly impact the data on the server, so be cautious
while making modifications.

3. Outline how to manage user accounts in MongoDB. [UN]


User Accounts
MongoDB provides the ability to add, remove, and configure users from the
MongoDB shell.
Listing Users
 User accounts are stored in the db.system.users collection of each database.
33
 To list users, change to the desired database in the MongoDB shell and execute
the show users command.
 Alternatively, you can use a query such as db.system.users.find() to get a cursor
object containing user documents.
 Example:
use admin
show users

Creating User Accounts


 User accounts can be created using the createUser() method in the MongoDB
shell.
 The createUser() method accepts a document object with fields specifying the
username, roles, and password.
 Fields used when creating users with db.createUser() method:
o user (string): Specifies a unique username.
o roles (array): Specifies an array of user roles. MongoDB provides various
roles with different privileges.
o pwd (hash or string, optional): Specifies the user password (stored as a
hash in the database).
 Example:
use test
db.createUser({
user: "testUser",
pwd: "test",
roles: ["readWrite", "dbAdmin"]
})

Removing Users
 Users can be removed using the removeUser(<username>) method in the
MongoDB shell.
 Switch to the database where the user exists and execute the removeUser()
method with the username as an argument.
 Example:
use testDB
db.removeUser("testUser")

4. Detail the procedure to configure access control in MongoDB. [UN]


Access Control
To configure access control in MongoDB, you need to create User
Administrator and Database Administrator accounts in the admin database. These
accounts will allow you to manage user accounts and perform administrative
functions within MongoDB.

Creating a User Administrator Account


 The User Administrator account is responsible for creating user accounts.
 Switch to the admin database in the MongoDB shell.
 Use the createUser() method to add a user with the userAdminAnyDatabase role.

34
 Example:
use admin
db.createUser({
user: "<username>",
pwd: "<password>",
roles: ["userAdminAnyDatabase"]
})
 Replace <username> and <password> with the desired values.

Turning on Authentication
 After creating the User Administrator account, restart the MongoDB database
with the --auth parameter.
 This parameter enforces authentication, requiring clients to provide a username
and password to access the database.
 When accessing MongoDB from the shell, you need to authenticate to the admin
database using the db.auth() method.
 Example:
use admin
db.auth("<username>", "<password>")
 Alternatively, you can authenticate when starting the MongoDB shell using the --
username and --password options.
 Example:
mongo --username "<username>" --password "<password>"

Creating a Database Administrator Account


 The Database Administrator account has extensive privileges to manage
databases, clusters, and replicas.
 Switch to the admin database in the MongoDB shell.
 Use the createUser() method to add a user with the necessary roles (e.g.,
readWriteAnyDatabase, dbAdminAnyDatabase, and clusterAdmin).
 Example:
use admin
db.createUser({
user: "dbadmin",
pwd: "test",
roles: ["readWriteAnyDatabase", "dbAdminAnyDatabase", "clusterAdmin"]
})
 Replace "dbadmin" and "test" with the desired username and password.

Authenticating as the Database Administrator


 After creating the Database Administrator account, authenticate to the admin
database using the db.auth() method.
 Example:
use admin
db.auth("dbadmin", "test")
 Alternatively, you can authenticate when starting the MongoDB shell using the --
username and --password options.

35
5. Discuss how can you administer databases in MongoDB using the MongoDB
shell. [UN]
Administering Databases
Displaying a List of Databases
To see a list of databases in the MongoDB system, use the command show
dbs.

Changing the Current Database


 To switch the current database in MongoDB, you can use either the
db.getSiblingDB(database) method or the use <database> command. For
example:
o db = db.getSiblingDB('testDB')
o use testDB

Creating Databases
MongoDB doesn't provide a command to explicitly create databases in the
shell. Instead, you can use the use <new_database_name> command to create a new
database handle. Keep in mind that the new database is not actually saved until you
add a collection to it.
For example:
use newDB
db.createCollection("newCollection")
To verify the existence of the new database, you can use show dbs.

Deleting Databases
To delete a database from the MongoDB shell, use the dropDatabase()
method. First, switch to the database you want to delete using use <database>, then
execute db.dropDatabase().
For example:
use newDB
db.dropDatabase()
Be aware that dropDatabase() removes the current database but does not change
the current database handle.

Copying Databases
To create a copy of a database in MongoDB, switch to the database you want
to copy and use the copyDatabase(origin, destination, [hostname]) command. The
origin parameter specifies the name of the database to copy, the destination
parameter specifies the name of the database to create on the current MongoDB
server. The optional hostname parameter is used when copying a database from a
different host. Example:
db.copyDatabase('customers', 'customers_archive')
This creates an exact duplicate of the 'customers' database with the name
'customers_archive' on the current server.

6. Indicate how can you manage the following operations in collections by using
the MongoDB shell. [UN]
a) Display b) Create c) Delete
a) Displaying a List of Collections in a Database
36
 To see a list of collections in a database, switch to that database using use
<database_name>.
 Use the command show collections to get the list of collections in the current
database.
 Example:
use test
show collections

b) Creating Collections
 Collections must be created before storing documents.
 Use the createCollection(name, [options]) method on the database handle to
create a collection.
 The name parameter specifies the name of the new collection.
 The optional options parameter is an object that defines the behavior of the
collection.
 Example:
db.createCollection("newCollection")

c) Deleting Collections
 To delete a collection, switch to the appropriate database, get the collection
object, and call the drop() function on that object.
 Example:
use testDB
show collections
coll = db.getCollection("newCollection")
coll.drop()
show collections

7. Express how can you manage the following operations in collections by using
the MongoDB shell. [UN]
a) Finding Document
b) Adding Documents
a) Finding Documents in a Collection
 Use the find(query) method on the collection object to query and retrieve
documents.
 The optional query parameter specifies a query document with fields and values
to match documents against.
 Omitting the query parameter returns all documents in the collection.
 Example:
use testDB
coll = db.getCollection("newCollection")
coll.find()
coll.find({speed: "120mph"})

b) Adding Documents to a Collection


 To add documents, use the insert(document) or save(document) method on the
collection object.
 The document parameter is a well-formatted JavaScript object that will be stored
37
in the collection.
 Example:
use testDB
coll = db.getCollection("newCollection")
coll.find()
coll.insert({vehicle: "plane", speed: "480mph"})
coll.insert({vehicle: "car", speed: "120mph"})
coll.insert({vehicle: "train", speed: "120mph"})
coll.find()

8. Discuss how you can manage the following operations in collections by using
the MongoDB shell.
a) Deleting Documents
b) Updating Document
a) Deleting Documents in a Collection
 To remove documents, use the remove(query) method on the collection object.
 The optional query parameter specifies a query document with fields and values
to match documents against.
 Omitting the query parameter removes all documents in the collection.
 Example:
use testDB
coll = db.getCollection("newCollection")
coll.find()
coll.remove({vehicle: "plane"})
coll.find()
coll.remove()
coll.find()

b) Updating Documents in a Collection


 Updates should generally be performed through your application. However, you
can manually update documents for administrative purposes.
 Use the save(object) method to save changes made to an object, or the
update(query, update, options) method to query and update documents.
 The query parameter specifies a query document with fields and values to match
documents against.
 The update parameter is an object that specifies the update operator and the
corresponding changes.
 The options parameter is an object with properties multi (to update multiple
documents) and upsert (to create a new document if none are found).
 Example:
use testDB
coll = db.getCollection("newCollection")
coll.find()
coll.update({speed: "120mph"}, {$set: {speed: "150mph", updated: true}},
{upsert: false, multi: true})
coll.save({"_id": ObjectId("52a0caf33120fa0d0e424ddb"), "vehicle": "plane",
"speed": "500mph"})
coll.find()

38
9. Develop a procedure to connect MongoDB from a Node.js application using the
MongoClient object, and list some important considerations such as write concern
and authentication. [AP]
Connecting to MongoDB from Node.js
 Install the mongodb module using npm.
 Access MongoDB from Node.js by opening a connection to the MongoDB server.
 Use the MongoClient class from the mongodb module.
 Two main methods to create connections: create an instance of MongoClient or
use a connection string.
 Perform database operations using the client object.

Understanding the Write Concern


 Write concern in MongoDB determines the level of guarantee for write operations.
 Stronger write concern ensures the write is successfully written to disk before
responding.
 Weaker write concern may respond before the write is fully committed to disk.
 Stronger write concerns increase the response time of write requests.
 Write concern levels in MongoDB driver:
 Level -1: Ignores network errors.
 Level 0: No write acknowledgement required.
 Level 1: Write acknowledgement requested.
 Level 2: Write acknowledgement requested across primary and one secondary
server.
 Level majority: Write acknowledgement requested across a majority of
servers in the replica set.

Connecting to MongoDB from Node.js Using the MongoClient Object


 To connect to MongoDB from a Node.js application, you can use the MongoClient
class.
 Create an instance of the MongoClient object using var client = new
MongoClient();.
 Open a connection to the MongoDB server using the connect(url, options,
callback) method.
 The connection URL consists of various components like host, port, username,
password, and database.
 Options can be provided as an object to customize the connection behavior.
 Important options include readPreference, ssl, poolSize, reconnectInterval,
auto_reconnect, readConcern, w (write concern), and more.
 The callback function receives an error as the first parameter and a Db object as
the second parameter upon successful connection.
 Use the Db object to access the MongoDB database and perform operations.
 Close the connection by calling close() on the Db object when finished.
 Authentication can be done either by including the username and password in the
connection URL or using the authenticate() method on the Db object.
 Examples of connecting to MongoDB using the MongoClient object with a
connection URL and authentication are provided.

39
 After successful connection and authentication, perform database operations
and handle logout and closure as needed.

10. Outline the different data types in MongoDB, and how are they represented in
BSON. [UN]
MongoDB Data Types
 MongoDB uses BSON (Binary JSON) to store JavaScript objects in binary form.
 BSON data format includes types that closely align with JavaScript types.
 Understanding MongoDB data types is important for querying specific properties
with desired value types.
 Each data type in MongoDB is assigned an integer ID number (1 to 255) used for
querying by type.
Here is a list of MongoDB data types along with their corresponding ID numbers:
 Double: 1  Regular Expression: 11
 String: 2  JavaScript: 13
 Object: 3  JavaScript (with scope): 15
 Array: 4  32-bit integer: 16
 Binary data: 5  Timestamp: 17
 Object ID: 7  64-bit integer: 18
 Boolean: 8  Decimal126: 19
 Date: 9  Min key: -1
 Null: 10  Max key: 127
 When working with different data types in MongoDB, it's important to consider
the comparison order. MongoDB follows a specific comparison order when
comparing values of different BSON types, ranging from lowest to highest.
 The comparison order is as follows:
o Min Key (internal type) o Binary Data
o Null o Object ID
o Numbers (32-bit integer, o Boolean
64-bit integer, Double) o Date, Timestamp
o String o Regular Expression
o Object o Max Key (internal type)
o Array

11. Create a simple application using MongoDB for Website Signup Form. [CR]
Installations
First, we need to include a few packages for our Nodejs application.
npm install express --save
Express allows us to set up middlewares to respond to HTTP Requests.
npm install body-parser --save
If you want to read HTTP POST data , you have to use the “body-parser” node module.
npm install mongoose --save
Mongoose is an object document modeling (ODM) layer which sits on the top of
Node’s MongoDB driver.
app.js This is the main executable application file
app.js
var express=require("express");
var bodyParser=require("body-parser");
40
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/gfg');
var db=mongoose.connection;
db.on('error', console.log.bind(console, "connection error"));
db.once('open', function(callback){
console.log("connection succeeded");
})
var app=express()
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/sign_up', function(req,res){
var name = req.body.name;
var email =req.body.email;
var pass = req.body.password;
var phone =req.body.phone;
var data = {
"name": name,
"email":email,
"password":pass,
"phone":phone
}
db.collection('details').insertOne(data,function(err, collection){
if (err) throw err;
console.log("Record inserted Successfully");
});
return res.redirect('signup_success.html');
})
app.get('/',function(req,res){
res.set({
'Access-control-Allow-Origin': '*'
});
return res.redirect('index.html');
}).listen(3000)
console.log("server listening at port 3000");

index.html
<!DOCTYPE html>
<html>
<head>
<title> Signup Form</title>
<link rel="stylesheet"
href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity=
"sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
41
crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<br>
<br>
<br>
<div class="container" >
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 main">
<form action="/sign_up" method="post">
<h1> Signup form </h1>
<input class="box" type="text" name="name" id="name"
placeholder="Name" required /><br>
<input class="box" type="email" name="email" id="email"
placeholder="E-Mail " required /><br>
<input class="box" type="password" name="password"
id="password" placeholder="Password " required/><br>
<input class="box" type="text" name="phone" id="phone"
placeholder="Phone Number " required/><br>
<br>
<input type="submit" id="submitDetails"
name="submitDetails" value="Submit" /><br>
</form>
</div>
<div class="col-md-3">
</div>
</div>
</div>
</body>
</html>

signup_success.html
<!DOCTYPE html>
<html>
<head>
<title> Signup Form</title>
<link rel="stylesheet"
href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity=
"sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
42
<br>
<br>
<br>
<div class="container" >
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 main">
<h1> Signup Successful</h1>
</div>
<div class="col-md-3">
</div>
</div>
</div>
</body>
</html>

style.css
.main{
padding:20px;
font-family: 'Helvetica', serif;
box-shadow: 5px 5px 7px 5px #888888;
}
.main h1{
font-size: 40px;
text-align:center;
font-family: 'Helvetica', serif;

}
input{
font-family: 'Helvetica', serif;
width: 100%;
font-size: 20px;
padding: 12px 20px;
margin: 8px 0;
border: none;
border-bottom: 2px solid #767474;
}
input[type=submit] {
font-family: 'Helvetica', serif;
width: 100%;
background-color: #767474;
border: none;
color: white;
padding: 16px 32px;
margin: 4px 2px;
border-radius: 10px;
}

43
Start the MongoDB.
Run app.js file
node app.js
Go to the browser and open http://127.0.0.1:3000/

This will add a record named “David Smith” in MongoDB.


Let’s have a check in MongoDB for the same record.
The record is now saved in the “gfg” database in “details” collection.

12. What is NoSQL? What is the need for it? Enlist the various features of NoSQL.
[RE]
NoSQL, which stands for "Not Only SQL," is a term used to refer to a class of
non-relational databases that provide a flexible and scalable approach to data
storage and retrieval. Unlike traditional relational databases (SQL databases), NoSQL
databases do not use the structured query language (SQL) and typically avoid the
use of fixed table schemas, which allows them to handle large volumes of data with
varying structures more efficiently.
The need for NoSQL arose due to the limitations of traditional SQL databases
in handling certain types of data and specific use cases. Here are some reasons why
NoSQL databases became popular:

Scalability:
NoSQL databases are designed to scale horizontally, meaning they can
distribute data across multiple servers and handle a growing amount of data and
traffic with ease. This makes them suitable for web applications and big data
scenarios.

Flexibility:
NoSQL databases do not enforce a rigid schema, allowing developers to store
data with varying structures without requiring modifications to the database schema.
This flexibility is particularly useful in scenarios where data is dynamic and might

44
evolve over time.

High Performance:
NoSQL databases are optimized for specific data access patterns and can
offer high read and write throughput. They are well-suited for applications that
require low-latency data retrieval, like real-time analytics or gaming.

Big Data and Unstructured Data Support:


NoSQL databases can handle semi-structured and unstructured data types,
such as JSON, XML, or key-value pairs, which are common in big data and modern
applications.

Distributed and Fault-Tolerant:


Many NoSQL databases are designed to operate in a distributed environment,
ensuring high availability and fault tolerance. They can replicate data across nodes
and maintain data consistency even in the face of node failures.

Schema Evolution:
NoSQL databases allow for easier schema evolution, making it more
straightforward to adapt to changing data requirements and application needs.

Cost-Effective:
NoSQL databases are often open-source or cloud-managed solutions, making
them more cost-effective than some commercial SQL databases.

Various features of NoSQL databases include:


 Schema Flexibility: NoSQL databases support dynamic and flexible schemas,
allowing data to be stored without a predefined structure.
 Horizontal Scalability: NoSQL databases are designed to scale horizontally by
adding more nodes to the cluster, providing the ability to handle large
amounts of data and traffic.
 No Joins: Unlike SQL databases, NoSQL databases generally do not support
complex joins between tables, which can simplify data retrieval in certain use
cases.
 High Availability: Many NoSQL databases offer built-in replication and data
distribution across nodes, ensuring high availability and fault tolerance.
 Eventual Consistency: Some NoSQL databases provide eventual consistency,
which means that data changes will propagate to all nodes over time,
ensuring eventual data synchronization.
 Key-Value Stores: One of the simplest forms of NoSQL databases, where data
is stored as key-value pairs, allowing for quick access to data based on keys.
 Document Stores: These databases store and retrieve data in the form of
documents (e.g., JSON or BSON), providing more flexibility in data
representation.
 Column-Family Stores: This type of NoSQL database stores data in column
families, which can be distributed across different nodes, enabling efficient
querying of specific data subsets.
 Graph Databases: Designed to work with graph data structures, these

45
databases are optimized for traversing and querying interconnected data.
 Time-Series Databases: Specialized databases for handling time-stamped
data, such as sensor data, logs, and financial data.

NoSQL databases come in various types, each tailored to different data


models and use cases, making them a valuable addition to the database landscape
alongside traditional SQL databases. The choice between NoSQL and SQL databases
depends on the specific requirements of the application and the nature of the data
being stored and processed.

13. Explain how to create users in MongoDB? Also enlist and explain various roles
of the users. [UN]
In MongoDB, user management is essential to control access to databases
and perform operations based on user privileges. To create users in MongoDB, you
need to have appropriate administrative privileges. Below are the steps to create
users in MongoDB:
 Connect to MongoDB: Open a terminal or command prompt and use the
MongoDB shell by typing mongo and pressing Enter. This will connect you to
the MongoDB instance.
 Switch to the admin database: Use the following command to switch to the
admin database, which is the default database for user management and
administrative tasks:
o use admin
 Create a new user: To create a new user, use the db.createUser() method. The
basic syntax to create a user is as follows:
db.createUser({
user: "username",
pwd: "password",
roles: ["role"]
})
Replace "username" with the desired username, "password" with the user's
password, and "role" with the appropriate role you want to assign to the user. Roles
are used to grant specific privileges to users. We'll explain various roles in the next
section.

Example of creating a user with appropriate privileges: Let's create a user with read
and write access to a specific database:
use mydatabase
db.createUser({
user: "myuser",
pwd: "mypassword",
roles: [
{ role: "readWrite", db: "mydatabase" }
]
})
This user, "myuser," will have read and write access to the "mydatabase"
database.
After creating the user, you can disconnect from the MongoDB shell using the
exit command.
46
Various Roles of Users in MongoDB:
 read: Provides read access to specific databases or collections but doesn't
allow write or modification operations.
 readWrite: Provides read and write access to specific databases or
collections, allowing both read and write operations.
 dbAdmin: Gives administrative access to a specific database. The user can
perform administrative tasks within that database, such as creating and
managing collections and indexes.
 dbOwner: Similar to dbAdmin, but additionally grants the ability to perform
any action on the specified database, including granting roles to other users.
 userAdmin: Allows the user to manage other users and their privileges within
a specific database.
 clusterAdmin: Provides full administrative access to the entire MongoDB
cluster, allowing management of replica sets and sharding.
 backup: Grants the ability to perform backups of the database.
 restore: Allows the user to restore data backups.
 root: The superuser role, which has full administrative access to the
MongoDB instance, including all databases.

It is important to grant only the necessary roles to users to follow the principle of
least privilege and enhance security. MongoDB provides a wide range of granular
roles to cater to different use cases and access control requirements. Always ensure
that sensitive credentials, such as passwords, are securely managed and never
shared in plaintext.

14. Show the steps to connect Node.js with MongoDB? [UN]


Connecting Node.js with MongoDB involves several steps to establish a
connection and interact with the database. Here's a step-by-step guide on how to do
it:

Install MongoDB and Node.js Driver:


 First, you need to have MongoDB installed on your system or access to a
remote MongoDB server.
 Install the MongoDB Node.js driver, mongodb, using npm (Node.js package
manager). Open your terminal or command prompt and run the following
command:
o npm install mongodb

Set up a Node.js Project:


 Create a new folder for your Node.js project and navigate into it using the
terminal.
 Initialize a new Node.js project by running the following command and
following the prompts (if any):
o npm init

Require the MongoDB Driver:


 In your Node.js application file (e.g., app.js), require the MongoDB driver using
47
the require function:
o const { MongoClient } = require('mongodb');

Create a Connection URL:


 Define the MongoDB connection URL, which includes the address of the
MongoDB server and the name of the database you want to connect to. For
example:
o const url = 'mongodb://localhost:27017/mydatabase';

Connect to MongoDB:
 Use the MongoClient.connect() method to establish a connection to the
MongoDB server:
MongoClient.connect(url, function (err, client) {
if (err) {
console.error('Error connecting to MongoDB:', err);
return;
}
console.log('Connected to MongoDB successfully!');
// Perform database operations here

client.close(); // Close the connection when done


});

Perform Database Operations:


Once the connection is established, you can perform various database
operations, such as inserting, updating, deleting, or querying data. Use the client
object obtained from MongoClient.connect() to interact with the database. Here's an
example of inserting a document into a collection:
const myCollection = client.db().collection('mycollection');
const newDocument = { name: 'John', age: 30 };
myCollection.insertOne(newDocument, function (err, result) {
if (err) {
console.error('Error inserting document:', err);
} else {
console.log('Document inserted successfully:', result.insertedId);
}});

Handle Errors and Close the Connection:


Always handle errors gracefully and ensure the database connection is closed
properly when you're done with the operations. In the example above, we used
client.close() to close the connection after performing the database operation.

Run the Node.js Application:


Save your changes in the app.js file and run your Node.js application using the
following command:
o node app.js

These are the basic steps to connect Node.js with MongoDB. Remember to
handle errors appropriately and use asynchronous programming patterns, such as
48
using async/await or callbacks, for database operations. Additionally, consider using
environment variables for sensitive information like the MongoDB connection URL
and credentials to enhance security.

15. Explain the db object and the methods associated with it. [UN]
In MongoDB, the db object is a JavaScript object that represents a database
within the MongoDB server. It is used to interact with the database, perform various
operations, and access collections within the database. The db object is available in
the MongoDB shell and can also be accessed in a Node.js application when using
the MongoDB driver.

Here are some of the common methods associated with the db object in MongoDB:
db.createCollection(name, options):
 Creates a new collection within the database with the specified name and
options.
 Example:
db.createCollection('users', { capped: true, size: 10000, max: 100 });

db.getCollection(name):
 Retrieves the specified collection from the database.
 Example:
const usersCollection = db.getCollection('users');

db.dropCollection(name):
 Deletes the specified collection from the database.
 Example:
db.dropCollection('users');

db.getCollectionNames():
 Returns an array of collection names present in the database.
 Example:
const collectionNames = db.getCollectionNames();

db.stats():
 Provides statistics about the current database, such as the number of
collections, data size, and index size.
 Example:
const stats = db.stats();

db.dropDatabase():
 Deletes the current database.
 Example:
db.dropDatabase();

db.runCommand(command):
 Executes a MongoDB command on the database.
 Example:
const command = { collStats: 'users' };
49
const result = db.runCommand(command);

db.getLastError():
 Returns the last error that occurred during the database operation.
 Example:
const lastError = db.getLastError();

==>X<==

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

1. Elaborate the common application settings provided by Express for configuring


its behaviour. [UN]
Implementing Express in Node.js
Express is a lightweight module that simplifies the usage of Node.js' http
module by providing an intuitive interface for handling server routes, responses,
cookies, and HTTP request statuses.
It allows you to configure the Express server, design routes, and utilize the
Request and Response objects to send and receive HTTP requests, while also
supporting the implementation of template engines for dynamic content rendering.

Getting Started with Express:


 To use Express in your Node.js projects, install the Express module by running
npm install express in the root of your project.
 After installation, create an instance of the Express class by importing the
module with var express = require('express'); and initializing var app = express();.

Configuring Express Settings:


 Express provides various application settings that control its behavior.
 You can use methods like set(setting, value), enable(setting), disable(setting),
get(setting), enabled(setting), and disabled(setting) to manage these settings.
 Examples of settings include:
o env: Defines the environment mode string, such as development, testing,
or production.
o trust proxy: Enables or disables reverse proxy support.
o jsonp callback name: Defines the default callback name for JSONP
requests.
o json replacer: Defines the JSON replacer callback function.
o json spaces: Specifies the number of spaces to use when formatting
JSON responses.
o case sensitive routing: Enables or disables case sensitivity in routing.
o strict routing: Enables or disables strict routing.
o view cache: Enables or disables view template compilation caching.
o view engine: Specifies the default template engine extension for rendering
templates.

50
o views: Specifies the path to look for view templates.

Starting the Express Server:


 To implement Express as the HTTP server for your Node.js application, create an
instance and start listening on a specific port.
 Use the app.listen(port) method, where port is the desired port number.
 This method binds the underlying HTTP connection to the port and starts
listening on it.
 The value returned by express() is a callback function that maps to the callback
function used in http.createServer() or https.createServer().

2. Explain the syntax for defining routes in Express? Can you provide an example of
a GET and POST route implementation. [UN]
Configuring Routes
A route is simply a definition that describes how to handle the path portion of
the URI in the HTTP request to the Express server.

Implementing Routes
i) Defining Routes:
 Routes are defined based on the HTTP request method and the specified path in
the URL.
 The syntax for defining routes in Express is: app.<method>(path, [callback . . .],
callback).
 <method> refers to the HTTP request method, such as GET or POST.
 The path parameter represents the URL path to be handled by the callback
function.
 Middleware functions can be included before the callback function to perform
additional processing.

ii) Handling Requests:


 The callback function, which takes a Request object (req) and a Response object
(res), handles the request and sends the response back to the client.
 Request object (req): Represents the incoming HTTP request and contains
information like request parameters, headers, and body.
 Response object (res): Allows sending the response back to the client, setting
headers, and handling the response body.

iii) Example GET and POST Routes:


 The provided code demonstrates basic implementation of GET and POST routes.
 app.get('/', function(req, res) {...}) handles the root path ("/") and sends the
response "Server Root" when accessed via a GET request.
 app.get('/login', function(req, res) {...}) handles the "/login" path and sends the
response "Login Page" for a GET request.
 app.post('/save', function(req, res) {...}) handles the "/save" path and sends the
response "Save Page" for a POST request.

iv) Route Handling:


 When the Express server receives an HTTP request, it searches for a route that
51
matches the HTTP method and path.
 If a matching route is found, a Request and Response object are created and
passed to the respective callback function(s) for further processing.

v) The app.all() Method:


 Express provides the app.all() method, which behaves similarly to app.post() and
app.get() methods.
 The difference is that the callback function defined with app.all() is called for
every request to the specified path, regardless of the HTTP method.
 The app.all() method can use the * wildcard in the path to handle all paths or
implement special functionality.
 For example, app.all('*', function(req, res) {...}) defines a global handler for all
paths, while app.all('/user/*', function(req, res) {...}) defines a global handler for
the "/user" path and its subpaths.

3. Discuss some commonly used properties and methods of the Request object in
Express. [UN]
Using Request objects
The Request object is commonly used in route handlers to access data and
metadata about the incoming HTTP request. It provides various properties and
methods that allow you to handle the request appropriately in your code. Here are
some of the commonly used properties of the Request object:
 originalUrl: The original URL string of the request.
 protocol: The protocol string used in the request, such as "http" or "https".
 ip: The IP address of the requester.
 path: The path portion of the request URL.
 hostname: The hostname of the request.
 method: The HTTP method used in the request, such as GET, POST, etc.
 query: The query string portion of the request URL.
 fresh: A Boolean property that is true when the "last-modified" header matches
the current request.
 stale: A Boolean property that is false when the "last-modified" header matches
the current request.
 secure: A Boolean property that is true when a TLS (Transport Layer Security)
connection is established.
 acceptsCharset(charset): A method that returns true if the character set specified
by the "charset" parameter is supported.
 get(header): A method that returns the value of the specified header.
These properties and methods allow you to access and utilize information about
the request, such as the URL, headers, query parameters, and more, to customize the
behavior of your application based on the incoming request.

4. Detail the following which are provided by the Response object in Express for
setting headers in the HTTP response. [UN]
a)Setting Headers b)Setting the Statusc)Sending Response
Using Response objects
The Response object passed to the route handler provides the necessary
functionality to build and send a proper HTTP response.
52
a )Setting Headers
The Response object in HTTP provides several helper methods to get and set
header values. Here are some important methods:
 get(header): This method returns the value of the specified header.
 set(header, value): This method sets the value of the specified header.
 set(headerObj): This method accepts an object containing multiple 'header':'value'
properties. Each header in the headerObj is set in the Response object.
 location(path): This method sets the location header to the specified path. The
path can be a URL path, a full URL, a relative path, or a browser action.
 type(type_string): This method sets the Content-Type header based on the
type_string parameter. The type_string can be a normal content type such as
application/json, a partial type such as png, or a file extension such as .html.
 attachment([filepath]): This method sets the Content-Disposition header to
'attachment'. If a filepath is specified, the Content-Type header is set based on
the file extension.

b) Setting the Status


To set the HTTP status for a response, you can use the status(number)
method on the Response object. The number parameter represents the HTTP
response status code defined in the HTTP specification.
Here are some examples of setting different status codes:
 res.status(200); // OK
 res.status(300); // Redirection
 res.status(400); // Bad Request
 res.status(401); // Unauthorized
 res.status(403); // Forbidden
 res.status(500); // Server Error

c) Sending Response
The send() method in Express is used to send the HTTP response back to the
client.
It can be used in two formats: res.send(status, [body]) and res.send([body]).
 In the first format, you can specify both the HTTP status code and the response
body. In the second format, the status code is set to 200 (OK) by default.
 The body parameter can be a string or a Buffer object.
 If you pass a Buffer object as the body, the Content-Type header is automatically
set to application/octet-stream unless you explicitly set it to another value.
 After the send() method completes, it sets the values of the res.finished and
res.headerSent properties.
 You can use res.finished to verify if the response was sent and res.headerSent to
check how much data was transferred.

5. Detail the following which are provided by the Response object in Express for
setting headers in the HTTP response. [UN]
a) Sending JSON Response
b) Sending Files

53
a) Sending JSON Response
Express provides the json() and jsonp() methods on the Response object to
facilitate sending JSON data back to the client.
 res.json(status, [object]): This method converts the JavaScript object into a JSON
string and sends it as the response body. The status parameter is optional and
represents the HTTP status code.
o For example: res.json(200, { message: 'Success' });
 res.json([body]): This format allows you to send the JSON response without
explicitly specifying the status code. The status code is set to 200 (OK) by default.
The body parameter is a JavaScript object that will be converted to JSON.
o For example: res.json({ message: 'Success' });
 res.jsonp(status, [object]): This method is similar to json(), but it supports the
JSONP (JSON with Padding) design pattern. It converts the JavaScript object into
a JSON string and wraps it in a function specified by the callback query
parameter. The status parameter is optional and represents the HTTP status
code.
o For example: res.jsonp(200, { message: 'Success' });
 res.jsonp([object]): This format allows you to send the JSONP response without
explicitly specifying the status code. The object parameter is a JavaScript object
that will be converted to JSON and wrapped in a function specified by the
callback query parameter.
o For example: res.jsonp({ message: 'Success' });

b) Sending Files
In Express, the sendfile(filepath) method on the Response object is a
convenient way to send files to the client.
The syntax for using the sendfile() method is as follows:
res.sendfile(path, [options], [callback])
 The path parameter represents the file path that you want to send to the client.
 The options parameter is an optional object that can contain the following
properties:
o maxAge: Specifies the maximum age for the content, allowing you to set
caching headers.
o root: Specifies a root path to support relative paths in the path parameter.
 The callback parameter is an optional function that is called when the file
transfer is complete. It accepts an error object as the only parameter.

6. Outline the following which are provided by the Response object in Express for
setting headers in the HTTP response. [UN]
a) Sending a Download Response
b) Redirecting the Response

a) Sending a Download Response


In Express, you can use the res.download() method to send a file to the client
as a downloadable attachment in the HTTP response. This method is similar to
res.sendfile(), but it sets the Content-Disposition header to indicate that the file
should be treated as an attachment.
The syntax for using the res.download() method is as follows:

54
res.download(path, [filename], [callback])
 The path parameter specifies the file to be sent to the client.
 The filename parameter is optional and allows you to specify a different filename
to be sent in the Content-Disposition header. If not provided, the original filename
from the path will be used.
 The callback parameter is an optional function that is executed once the file
download has completed.

b) Redirecting the Response


Express provides the res.redirect(path) method to handle redirecting the
client's request to a different location. This can be useful when you want to redirect
the user to a different page or server.
The syntax for using the res.redirect() method is as follows:
res.redirect(path)
 The path parameter specifies the new location to redirect the request to.
 The path can be an absolute URL (e.g., 'http://example.com'), a relative path on
the same server (e.g., '/newpath'), or a browser action such as 'back'.

7. What is class? How to use in TypeScript? Examine it with suitable examples.


[AN]
Implementing Classes
TypeScript introduced classes TypeScript introduced classes to avail the
benefit of object-oriented techniques like encapsulation and abstraction.
The class in TypeScript is compiled to plain JavaScript functions by the
TypeScript compiler to work across platforms and browsers
A class can include the following:
 Constructor
 Properties
 Methods

Example: Class
class Employee {
empCode: number;
empName: string;

constructor(code: number, name: string) {


this.empName = name;
this.empCode = code;
}

getSalary() : number {
return 10000;
}
}

8. What is interface? Explain the use of interface in TypeScript with suitable


example. [UN]
Understanding Interfaces
Interfaces are a fundamental part of TypeScript. They allow you to have a set
55
structure for an application.
Example: Interface
interface Person {
hairColor: string;
age: number;
}

Implementing Modules
Modules in TypeScript allow you to organize your code over multiple files.
Example: Module
module module_name{
class xyz{
export sum(x,y){
return x+y
}
}

9. Illustrate the various Key Components of Angular with a neat diagram. [UN]
Angular building blocks
 Modules (NgModule): Angular
applications are organized into
modules, which serve as
containers for related
components, services, and other
code files.
 Components: Components are
the building blocks of the
application's user interface. They
encapsulate logic, templates, and styles, and interact with data and user actions.
 Templates: Templates define the structure and layout of the user interface. They
use Angular-specific syntax and are responsible for rendering dynamic content.
 Metadata: Metadata provides Angular with information about a class or
component. It is defined using decorators and helps Angular understand how to
process and use the component.
 Data Binding: Data binding keeps the component and template in sync, allowing
for seamless transfer of data. Angular supports interpolation, property binding,
event binding, and two-way binding.
 Directives: Directives modify the DOM based on instructions provided by Angular.
Structural directives manipulate the structure of the template, while attribute
directives modify element properties.
 Services: Services are reusable components that handle specific functionality
such as data manipulation, API calls, and authentication. They can be shared
across multiple components.
 Dependency Injection: Angular's dependency injection pattern resolves and
provides dependencies to components and services, promoting loose coupling
and reusability.

10. Make use of various binding available in Angular to dynamically add or remove
CSS class from an element. [AP]
56
In Angular, there are several types of binding that facilitate the
synchronization of data between the component and the template. Each type serves
a specific purpose and allows for dynamic updates in the user interface. Here are the
various types of binding in Angular:

String Interpolation ({{ }}):


Interpolation allows you to embed expressions within double curly braces in the
template. It evaluates the expression and replaces it with the resulting value. It is
primarily used for displaying dynamic data in the template.

Example: <h1>{{ title }}</h1>

Property Binding ([ ]):


Property binding allows you to bind a component property to an element property in
the template. It sets the value of the element property based on the component
property, and any changes to the component property will reflect in the element.

Example: <img [src]="imageUrl">

Event Binding (( )):


Event binding enables you to respond to user actions, such as button clicks or input
events. It binds a component method to an event in the template, and when the event
occurs, the associated method is executed.

Example: <button (click)="handleClick()">Click me</button>

Two-Way Binding ([()]):


Two-way binding combines both property binding and event binding into a single
syntax. It allows for synchronization of data in both directions, from the component
to the template and vice versa. Changes in either the component property or the
template element will update both.

Example: <input [(ngModel)]="name">

Attribute Binding ([attr. ]):


Attribute binding allows you to set attributes dynamically on an element in the
template. It binds a component property to an attribute value, and the attribute is
updated whenever the component property changes.

Example: <input [attr.disabled]="isDisabled">

Class Binding ([class. ]):


Class binding allows you to dynamically add or remove CSS classes from an element
based on component properties. It binds a component property to a class name, and
the class is applied or removed based on the truthiness of the property.

Example: <div [class.error]="hasError">Error message</div>

Style Binding ([style. ]):


57
Style binding enables you to apply dynamic styles to an element based on
component properties. It binds a component property to a CSS style property, and
the style is updated based on the value of the property.

Example: <div [style.backgroundColor]="backgroundColor">Styled div</div>

11. Explain the built-in attribute directives in Angular with suitable example. [UN]
Directives are classes that add additional behavior to elements in your
Angular applications. Use Angular's built-in directives to manage forms, lists, styles,
and what users see.

The different types of Angular directives are as follows:


DIRECTIVE TYPES DETAILS
Components Used with a template. This type of directive is the most
common directive type.
Attribute directives Change the appearance or behavior of an element,
component, or another directive.
Structural directives Change the DOM layout by adding and removing DOM
elements.

Built-in attribute directives


Attribute directives listen to and modify the behavior of other HTML elements,
attributes, properties, and components.
Many NgModules such as the RouterModule and the FormsModule define
their own attribute directives. The most common attribute directives are as follows:
COMMON DIRECTIVE DETAILS
NgClass Adds and removes a set of CSS classes.
NgStyle Adds and removes a set of HTML styles.
NgModel Adds two-way data binding to an HTML form
element.

12. Explain the properties and methods of request object. [UN]


The req object represents the HTTP request and has properties for the
request query string, parameters, body, HTTP headers, and so on.

Request Object Properties


Following is the list of few properties associated with request object.
req.app - This property holds a reference to the instance of the express application
that is using the middleware.
req.body - Contains 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 - When using cookie-parser middleware, this property is an object that
contains cookies sent by the request.
req.ip - The remote IP address of the request.
req.path - Contains the path part of the request URL.
req.route - The currently-matched route, a string.

58
Request Object Methods
req.accepts(types)
This method checks if the specified content types are acceptable, based on
the request’s Accept HTTP header field. Following are a few examples −
// Accept: text/html
req.accepts('html');
// => "html"
// Accept: text/*, application/json
req.accepts('html');
// => "html"
req.accepts('text/html');
// => "text/html"

req.get(field)
This method returns the specified HTTP request header field. Following are a
few examples −
req.get('Content-Type');
// => "text/plain"
req.get('content-type');
// => "text/plain"
req.get('Something');
// => undefined

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. Following are
few a examples −
// With Content-Type: text/html; charset=utf-8
req.is('html');
req.is('text/html');
req.is('text/*');
// => true

59
13. Explain the properties and methods of response object. [UN]
The Response object (res) specifies the HTTP response which is sent by an
Express app when it gets an HTTP request.
Response Object Properties
Let's see some properties of response object.
res.app - It holds a reference to the instance of the express application that is using
the middleware.
res.headersSent - It is a Boolean property that indicates if the app sent HTTP
headers for the response.
res.locals - It specifies an object that contains response local variables scoped to
the request

Response Object Methods


Response Append method
Syntax:
res.append(field [, value])
This method appends the specified value to the HTTP response header field.
That means if the specified value is not appropriate then this method redress that.
Examples:
res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
res.append('Warning', '199 Miscellaneous warning');

Response Attachment method


Syntax:
res.attachment([filename])
This method facilitates you to send a file as an attachment in the HTTP
response.
Examples:
res.attachment('path/to/js_pic.png');

Response Cookie method


Syntax:
res.cookie(name, value [, options])
This method is used to set a cookie name to value. The value can be a string
or object converted to JSON.
Examples:
res.cookie('name', 'Aryan', { domain: '.xyz.com', path: '/admin', secure:
true });
res.cookie('Section', { Names: [Aryan,Sushil,Priyanka] });
res.cookie('Cart', { items: [1,2,3] }, { maxAge: 900000 });

Response End method


Syntax:
res.end([data] [, encoding])
This method is used to end the response process.
Example:
res.end();
res.status(404).end();

60
Response Get method
Syntax:
res.get(field)
This method provides HTTP response header specified by field.
Example:
res.get('Content-Type');

Response Send method


Syntax:
res.send([body])
This method is used to send HTTP response.
Examples:
res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('
.....some html
');

Response Set method


Syntax:
res.set(field [, value])
This method is used to set the response of HTTP header field to value.
Examples:
res.set('Content-Type', 'text/plain');

res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
})

Response Status method


Syntax:
res.status(code)
This method sets an HTTP status for the response.
Examples:
res.status(403).end();
res.status(400).send('Bad Request');

14. Build the code in TypeScript to implement the simple arithmetic calculator
application. (Make use of interface) [CR]
We'll implement the basic operations of addition, subtraction, multiplication,
and division.
Step 1: Set up the project
 Create a new folder for your project.
 Open a code editor (e.g., Visual Studio Code) and navigate to the project
directory.
 Initialize a new TypeScript project:
o Open the terminal in your code editor and run the following command
to create a package.json file:
61
npm init -y
 Install TypeScript:
npm install typescript --save-dev
 Create a new file named app.ts in your project directory.
Step 2: Write the TypeScript code
 Open app.ts and add the following code:
// Define an interface for the calculator
interface Calculator {
add: (a: number, b: number) => number;
subtract: (a: number, b: number) => number;
multiply: (a: number, b: number) => number;
divide: (a: number, b: number) => number;
}

// Implement the calculator interface


const calculator: Calculator = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b,
divide: (a, b) => (b !== 0 ? a / b : NaN),
};

// Test the calculator functions


const num1 = 10;
const num2 = 5;
console.log(`Addition: ${calculator.add(num1, num2)}`);
console.log(`Subtraction: ${calculator.subtract(num1, num2)}`);
console.log(`Multiplication: ${calculator.multiply(num1, num2)}`);
console.log(`Division: ${calculator.divide(num1, num2)}`);

In the above code, we first define an interface named Calculator that specifies
the structure of our calculator with four methods: add, subtract, multiply, and divide.
Each method takes two numbers as parameters and returns the result of the
corresponding arithmetic operation.
We then create an object named calculator that implements the Calculator
interface. Each method in the calculator object provides the implementation for the
corresponding arithmetic operation.
Finally, we test the calculator functions by performing arithmetic operations
on num1 and num2 and display the results in the console.

Step 3: Compile and run the TypeScript code


 Open the terminal in your code editor if it's not already open.
 Compile the TypeScript code to JavaScript:
npx tsc app.ts
This will generate an app.js file in your project directory.
 Run the JavaScript code:
node app.js

Results of the arithmetic operations displayed in the console:


62
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
15. Explain the angular architecture with suitable block diagram. [UN]
Angular follows a modular architecture that promotes the organization of
code into reusable and manageable pieces. This architecture is based on various
building blocks, including modules, templates, components, services, and more. Let's
take a closer look at each of these components:

Modules:
 Modules in Angular are
containers for related
components, directives, services,
and other features that help
organize an Angular application
into functional blocks.
 Each Angular application has at
least one root module (usually
named AppModule) that serves
as the entry point to the
application.
 Modules help in lazy loading,
optimizing application loading
time, and creating isolated contexts for features.

Components:
 Components are the building blocks of an Angular application's UI. They
represent reusable and self-contained user interface elements.
 Each component consists of a template (HTML), a TypeScript class
(Component class), and styles (CSS or SCSS).
 Components handle data and user interactions, and they can be reused
throughout the application.

Templates:
 Templates define the HTML markup that represents the view of a component.
They contain placeholders (data binding and directives) to interact with
component logic and display dynamic content.

Directives:
 Directives are instructions in the DOM that modify the behavior or appearance
of elements.
 Angular has two types of directives: Structural Directives (e.g., ngIf, ngFor,
ngSwitch) and Attribute Directives (e.g., ngStyle, ngClass).

Services:
 Services are classes that provide functionality that can be shared across
components.

63
 Services are used to encapsulate data manipulation, business logic, HTTP
requests, and other shared operations.
 Components can inject services through dependency injection to use their
functionality.

Routing:
 Angular provides a powerful routing module (RouterModule) that allows
navigation between different views or pages of an application.
 The routing module maps URLs to specific components and enables deep
linking within the application.

Dependency Injection:
 Dependency Injection (DI) is a fundamental concept in Angular, facilitating the
creation and management of dependencies between different parts of the
application.
 Angular's DI system injects the required dependencies into components,
services, and other classes.

Angular's modular architecture encourages the separation of concerns,


reusability, maintainability, and scalability of the application. It enables developers to
build complex applications in a structured and organized way. By dividing the
application into smaller, focused building blocks, developers can efficiently manage
and extend the codebase.

==>X<==

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

1. Explain the MERN stack, and how does it differ from other web development
stacks? [UN]
The MERN stack is a popular and modern web development stack used to
build full-stack web applications. It consists of four main components:
 MongoDB: MongoDB is a
NoSQL database that stores
data in JSON-like documents,
making it highly flexible and
scalable. It is known for its
ease of use, as it allows
developers to work with data in
a more natural and object-
oriented manner.
 Express: Express is a fast and
minimalist web application
framework for Node.js. It
64
provides a set of features for building web servers and RESTful APIs. Express
simplifies routing, middleware creation, and handling HTTP requests and
responses.
 React: React is a JavaScript library for building user interfaces. It allows
developers to create reusable UI components, making the development
process more efficient. React's virtual DOM enables fast and efficient updates
to the actual DOM, leading to better application performance.
 Node.js: Node.js is a server-side JavaScript runtime built on Chrome's V8
JavaScript engine. It allows developers to execute JavaScript code on the
server, enabling the development of server-side applications. Node.js is non-
blocking and event-driven, making it well-suited for building scalable and real-
time applications.

How MERN differs from other web development stacks:


 Front-end Focus: Unlike traditional stacks where the front-end and back-end
technologies may vary, MERN is a full-stack JavaScript solution. React
handles the front-end, and Node.js with Express manages the back-end,
allowing developers to use a consistent language and ecosystem throughout
the entire application.
 Real-time Capabilities: The MERN stack, powered by Node.js, is particularly
suitable for building real-time applications like chat applications, collaborative
tools, or gaming platforms that require instant data updates.
 Scalability: MERN applications can be easily scaled horizontally due to the
non-blocking nature of Node.js and the flexibility of MongoDB, which can
handle large amounts of data efficiently.
 Development Efficiency: The MERN stack promotes code reusability with
React components and offers a wide range of libraries and packages
available through npm, streamlining the development process.
 JSON-based Data Flow: Data flow between components in the MERN stack is
typically handled using JSON (JavaScript Object Notation), making it easier to
manage and manipulate data across the application.
 NoSQL Database: MongoDB, being a NoSQL database, allows for more
flexible and dynamic data models compared to traditional relational
databases, which can be beneficial for certain types of applications and data
structures.

2. Demonstrate how do you manage state in React applications? Compare and


contrast local state and global state management solutions. [UN]
In React applications, state management is crucial for handling and
maintaining data that can change over time, influencing the behavior and appearance
of the user interface. There are two main approaches to managing state in React:

Local State:
Local state refers to managing state within a single component. State data is
stored and managed within the component itself using React's built-in useState hook
(for functional components) or this.state (for class components). Local state is
appropriate when the state data is only relevant and used within a specific
component and doesn't need to be shared with other components.

65
Pros of Local State:
 Simple and straightforward to implement.
 Isolated to a specific component, reducing the risk of unintended side effects.
 Good for managing component-specific data and behavior.

Cons of Local State:


 Difficult to share state data with other components that might need access to the
same information.
 Might lead to prop-drilling (passing data through multiple layers of components)
if parent components need access to the child's state.

Global State Management Solutions:


Global state management solutions are used to share state data across
multiple components in a React application. These solutions are especially useful
when components need to interact and share data with one another but don't have a
direct parent-child relationship. Some popular global state management solutions in
React are Redux and the Context API.
Redux:
 Redux is a predictable state container that manages the state of the entire
application in a single global store.
 Components can dispatch actions to update the state, and changes are
propagated to all components that subscribe to the relevant parts of the state.
 Redux uses a centralized approach to manage the state, making it easier to
track and debug changes.

Context API:
 The Context API is a built-in solution provided by React, allowing developers to
create a global state and share it with components in the component tree.
 It provides a way to pass data down the component tree without prop drilling.
 While not as powerful as Redux, it's a lighter option for simpler applications
that don't require the full feature set of Redux.

Pros of Global State Management Solutions:


 Allows data sharing and communication between components that are not
directly related.
 Facilitates a more organized and scalable approach for state management in
large applications.
 Helps avoid prop-drilling and keeps the component tree cleaner.

Cons of Global State Management Solutions:


 Can introduce additional complexity, especially for smaller applications with
minimal inter-component interactions.
 Learning curve and boilerplate code might be higher, especially for Redux.

3. Summarize the advantages and disadvantages of using class components in


modern React applications. [UN]
In React, components are the building blocks of user interfaces. They are
reusable, self-contained pieces of code that define the structure, behavior, and
66
appearance of different parts of a web application. React components can be either
class components (traditional syntax) or functional components (modern syntax
with hooks).

Class Components:
Class components are ES6 classes that extend React.Component. They
manage their own state and lifecycle methods, making them suitable for more
complex components. Here's an example of a class component:
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}

Functional Components with Hooks:


Functional components are simpler and more concise. With the introduction
of hooks in React 16.8, functional components can manage state and handle side
effects, making them as capable as class components. Here's the same example
using a functional component with hooks:
import React, { useState } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount(count + 1);
};

return (
<div>
<p>Count: {count}</p>
<button onClick={incrementCount}>Increment</button>
</div>
);
}
In both examples, the component renders a counter with a button that
67
increments the count when clicked. The primary difference between class
components and functional components with hooks is the syntax and how state and
lifecycle methods are handled.
In general, functional components with hooks are becoming the preferred way
to write components in modern React applications due to their simplicity, improved
performance, and the capabilities provided by hooks (e.g., useState, useEffect,
useContext, etc.). However, class components are still used in certain scenarios,
especially when working with legacy code or interacting with third-party libraries that
rely on class components.

4. Outline the React component lifecycle, and what are the three main phases that
components go through? [UN]
In React, component lifecycle refers to the different phases or stages a
component goes through during its existence. These phases allow components to
be initialized, rendered, updated, and eventually unmounted from the DOM.
Understanding the component lifecycle is crucial for managing state, side effects,
and optimizing performance in React applications.

Mounting Phase:
 constructor(): The constructor is called when the component is being initialized.
It is used to set up the component's initial state and bind event handlers.
 componentWillMount(): This method was deprecated in React 16.3 and removed
in React 17. It was called just before the component is rendered for the first time,
both on the server and the client.
 render(): The render method is responsible for returning the JSX representation
of the component. It must be a pure function and should not modify the
component's state.

Updating Phase:
 componentWillReceiveProps(nextProps): This method was deprecated in React
16.3 and removed in React 17. It was called when the component is receiving
new props and can be used to update the state based on the new props.
 shouldComponentUpdate(nextProps, nextState): This method allows developers
68
to control whether the component should be re-rendered or not. By default, it
returns true, but it can be overridden to optimize performance by avoiding
unnecessary re-renders.
 componentWillUpdate(nextProps, nextState): This method was deprecated in
React 16.3 and removed in React 17. It was called just before the component is
updated and can be used for tasks that need to be performed before a re-render.
 render(): The render method is called again to update the component's UI with
the new state or props.

Unmounting Phase:
 componentWillUnmount(): This method is called just before the component is
unmounted from the DOM. It is used for cleaning up resources, such as canceling
network requests or removing event listeners.

With the introduction of React 16.3, some lifecycle methods were deprecated in
favor of new and more expressive APIs called "React Hooks." Hooks allow
developers to manage state and side effects in functional components, making the
component lifecycle more consistent and predictable.

With React Hooks, the most commonly used lifecycle methods are replaced by
the following hooks:

 useState: Replaces the need for constructor and this.state, allowing functional
components to manage state.
 useEffect: Replaces componentDidMount, componentDidUpdate, and
componentWillUnmount, providing a way to handle side effects and perform
cleanup.
 useContext: Replaces contextType and Consumer, allowing functional
components to access context data.
 useReducer: Provides an alternative to setState for managing more complex
state logic.
 useMemo and useCallback: Help optimize performance by memoizing values
and functions.

5. Create a simple application to demonstrate the React Router. [CR]


Create a New React App
Start by creating a new React app using Create React App:
npx create-react-app react-router-example
cd react-router-example

Install React Router


Next, install React Router in your project:
npm install react-router-dom

Create Components
Create three components for the Home, About, and Contact pages in a new
components folder:
 Create a Home.js component:

69
import React from 'react';
const Home = () => {
return <div>Welcome to the Home Page!</div>;
};
export default Home;

 Create an About.js component:


import React from 'react';
const About = () => {
return <div>About Us: We are a cool company!</div>;
};
export default About;

 Create a Contact.js component:


import React from 'react';
const Contact = () => {
return <div>Contact Us: Email us at [email protected]</div>;
};
export default Contact;
Configure Routes
In the src folder, create a new App.js file with the following content:
import React from 'react';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-
dom';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';

const App = () => {


return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>

<hr />

<Switch>
70
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</div>
</Router>
);
};

export default App;


In this configuration, we use the BrowserRouter as the router, and we define
three routes: one for the Home component (/), one for the About component
(/about), and one for the Contact component (/contact). The Link components
provide navigation links to these routes, and the Switch component ensures that only
one route is matched at a time.

Update index.js
Update the src/index.js file to use the App component:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root'));
Run the App
Finally, start your React application:
npm start

The application should start, and you should see a navigation bar with links to
the Home, About, and Contact pages. Clicking on each link should display the
corresponding content for the respective route.
You have now created a simple multi-page React application using React
Router. The application allows users to navigate between different pages without full
page reloads, providing a seamless user experience.

6. Summarize the role of MongoDB in the MERN stack. Discuss the benefits of
using a NoSQL database like MongoDB in a full-stack web application. [UN]
In the MERN stack (MongoDB, Express, React, Node.js), MongoDB plays the
role of the database, serving as the "M" or the backend component for data storage.
MongoDB is a popular NoSQL database that stores data in a flexible, schema-less
format known as BSON (Binary JSON). It is a critical component in the MERN stack
architecture, enabling developers to store and retrieve data efficiently for full-stack
web applications.

Benefits of using MongoDB (a NoSQL database) in a MERN stack application:


71
 Schema Flexibility:
 MongoDB is a schema-less database, which means it allows developers to store
data without a predefined schema. This flexibility is particularly advantageous
during the early stages of development when the data structure might be subject
to frequent changes. It also simplifies handling data with varying attributes
across different documents, making it easier to adapt to evolving application
requirements.
 Scalability:
 MongoDB's horizontal scalability is a significant advantage for modern web
applications that experience high data growth and increased traffic. It can easily
distribute data across multiple servers (sharding) to handle large-scale
applications and workloads.
 Query Performance:
 MongoDB's document-based storage and indexing system offer excellent query
performance. Its BSON format and flexible data model allow for efficient storage
and retrieval of JSON-like data. Additionally, MongoDB supports various types of
indexes to optimize queries, making it well-suited for real-time applications.
 Ease of Development:
 The JSON-like BSON data format in MongoDB is closely aligned with JavaScript,
making it easy for developers to work with the database using familiar data
structures. This alignment simplifies the development process and reduces the
need for complex object-relational mapping (ORM) libraries.

 Horizontal Scaling:
MongoDB's distributed architecture allows it to scale horizontally, meaning it can
handle increased traffic and data volume by adding more servers to the cluster. This
enables developers to build applications that can grow with demand, ensuring a
smooth user experience as the user base expands.
 Geospatial Capabilities:
MongoDB has built-in support for geospatial indexing and querying, making it a
suitable choice for location-based applications and services. It allows developers to
store and retrieve geospatial data efficiently.
 Document-Oriented Model:
MongoDB stores data in JSON-like documents, which can represent complex
data structures. This document-oriented model aligns well with modern web
development practices, where data objects often have nested or hierarchical
relationships.
 Aggregation Framework:
MongoDB provides a powerful aggregation framework that allows developers to
perform complex data transformations, filtering, grouping, and calculations directly
within the database. This capability reduces the need for additional processing on
the application server, improving overall performance.
 Community and Ecosystem:
MongoDB has a vibrant and active community with extensive documentation,
tutorials, and resources available. Additionally, it integrates well with popular
frameworks and libraries, providing support for various programming languages.
 Auto-Sharding:
MongoDB's auto-sharding feature allows for automatic data distribution across
72
shards, simplifying the process of scaling the database horizontally. This ensures
even data distribution and optimal performance in large-scale deployments.

7. Illustrate how to design your REST API Architecture [UN]


REST is another acronym, this time for Representational State Transfer. In
simple terms, it is a way of thinking about APIs – one of many potential ways.
However, it is one of the most widely adopted, because it is easy to understand,
implement, and scale.
REST promotes the concept of resource. A resource is “something” you can
perform actions onto. What that something is, of course, depends on what your API
is doing. Yet, it represents an object – either physical or abstract.
If we go back to our previous example of hotel reservations, we can identify
many potential resources. To start, we can identify the hotel resource. On that, we
should be able to get the list of hotels and get the details of each individual hotel,
including if they accept reservations. Yet, the most crucial resource for that app
would be the reservation itself. On this we have more actions available: we can
create, edit, and delete one. Furthermore, we may want to get the details of an
existing reservation or see all of our reservations.
This approach is modular because as our application grows we can add more
and more resources, in a way that is not strictly interdependent with existing ones.
For example, we could add an additional resource room in that example, and if we
move on to booking flights also a flight resource could be nice.

HTTP Methods (Apr/May 2021)


So far, we identified only how to name resources, but how can the client tell
us what action is being requested on the resource? The client does that thanks to
the HTTP Method.
HTTP offers several standard methods, that work pretty well with resources
because they represent exactly what we would like to do on a resource.

Method Description
GET If on a specific resource (with ID), the user is requesting the details
about that resource.
When on a resource collection (no ID), the user is requesting the list
of instances of that resource.
POST Create a new resource. You call this method always without ID.
PUT Update an existing resource. You call this method always with ID.
DELETE Delete an existing resource. You call this method always with ID.
HEAD Similar to get, but you get only the most important details of the
resources – not all. Designed if you want to do a list of resources
73
with basic items so that it is faster to load.

HTTP offers us also other methods, but the ones you see in the table will do
for us. As a result, we are going to call always the same URLs, but every time with a
different method depending on what we want to do. Take a look at the examples
below.

HEAD https://api.example.com/reservations
GET https://api.example.com/reservations
GET https://api.example.com/reservations/5fafa40495101e4dd018d027
POST https://api.example.com/reservations
PUT https://api.example.com/reservations/5fafa40495101e4dd018d027
DELETE https://api.example.com/reservations/5fafa40495101e4dd018d027

Our API is starting to take shape, at least when it comes to requests. In fact,
we now have a clear idea of what kind of requests we should expect (and thus
implement in our backend). The next step is to think about the response.

Formatting the Response


The user asks something and expects some sort of response. Most often, you
should provide some information inside the body of the response. For example, if the
user requests the details of a resource, you should provide them when you reply.
The way to do it is with JSON. JSON – JavaScript Object Notation – is a
convenient way to represent complex data in a way that is structured and easy to
understand, both for the user and for the computer. So, whenever you put something
in the body of the request, it should be JSON.
The other thing you need to take care of is the HTTP Status. In fact, with
HTTP you can define the status of every request when you provide a response to it.
Was it successful? Did it have some errors? You can provide some more details with
a single number.
When defining the HTTP Status, keeps things simple. Ideally, you should use
only a few statuses, and if you need to add some more descriptions in the body.

Status Description
200 OK, the request was successful and the response contains the
requested data. You should use it for success on any requests but
POST.
201 CREATED, the resource has been created. Hence, use it on success
only for POST.
400 BAD REQUEST, generic issue in user input or request.
401 UNAUTHORIZED, the user is not authenticated.
403 FORBIDDEN, the user is authenticated but has no access to this
resource.
500 SERVER ERROR, ideally, you should have the least possible of those.
Whenever you have one, it means trouble.

Some people also use 204 NO CONTENT with DELETE requests. This means
that the response is correctly coming with an empty body. While this is a valid
approach, I recommend instead returning the entire deleted resource in that case.
74
Hence, there is no need to use that status code.

8. Explain the purpose and usage of the Express.js Request and Response objects
in an Express application. Provide examples of scenarios where you would use
these objects and their associated properties. [UN]
Express.js Request Object
Express.js Request and Response objects are the parameters of the callback
function which is used in Express applications.

The express.js request object represents the HTTP request and has properties for
the request query string, parameters, body, HTTP headers, and so on.
Syntax:

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


// --
})

Express.js Request Object Properties


The following table specifies some of the properties associated with request object.
Properties Description
req.app This is used to hold a reference to the instance of the express
application that is using the middleware.
req.baseurl It specifies the URL path on which a router instance was
mounted.
req.body It contains 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 When we use cookie-parser middleware, this property is an
object that contains cookies sent by the request.
req.fresh It specifies that the request is "fresh." it is the opposite of
req.stale.
req.hostname It contains the hostname from the "host" http header.
req.ip It specifies the remote IP address of the request.
req.ips When the trust proxy setting is true, this property contains an
array of IP addresses specified in the? x-forwarded-for?
request header.
req.originalurl This property is much like req.url; however, it retains the
original request URL, allowing you to rewrite req.url freely for
internal routing purposes.
req.params An object containing properties mapped to the named route
?parameters?. For example, if you have the route /user/:name,
then the "name" property is available as req.params.name.
This object defaults to {}.
req.path It contains the path part of the request URL.
req.protocol The request protocol string, "http" or "https" when requested
with TLS.
req.query An object containing a property for each query string
parameter in the route.

75
Properties Description
req.route The currently-matched route, a string.
req.secure A Boolean that is true if a TLS connection is established.
req.signedcookies When using cookie-parser middleware, this property contains
signed cookies sent by the request, unsigned and ready for
use.
req.stale It indicates whether the request is "stale," and is the opposite
of req.fresh.
req.subdomains It represents an array of subdomains in the domain name of
the request.
req.xhr A Boolean value that is true if the request's "x-requested-with"
header field is "xmlhttprequest", indicating that the request
was issued by a client library such as jQuery

Express.js Request Object


It sends response back to the client browser.
It facilitates you to put new cookies value and that will write to the client browser
(under cross domain rule).
Once you res.send() or res.redirect() or res.render(), you cannot do it again,
otherwise, there will be uncaught error.
Response Object Properties
Let's see some properties of response object.

Response Download method


Syntax:
 res.download(path [, filename] [, fn])
This method transfers the file at path as an "attachment" and enforces the
browser to prompt user for download.

Response End method


Syntax:
 res.end([data] [, encoding])
This method is used to end the response process.

Response JSON method:


Syntax:
 res.json([body])
This method returns the response in JSON format.
Example:
res.json(null)
res.json({ name: 'ajeet' })

Response Redirect method


Syntax:
 res.redirect([status,] path)
This method redirects to the URL derived from the specified path, with
specified HTTP status
Examples:

76
res.redirect('http://example.com');

Response Render method


Syntax:
 res.render(view [, locals] [, callback])
This m ethod renders a view and sends the rendered HTML string to the client.

Response Send method


Syntax:
 res.send([body])
This method is used to send HTTP response.
Examples:
res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('
.....some html
');

Response sendFile method


Syntax:
 res.sendFile(path [, options] [, fn])
This method is used to transfer the file at the given path. It sets the Content-Type
response HTTP header field based on the filename's extension.
Examples:
res.sendFile(fileName, options, function (err) {
// ...
});

9. Explain the concept of passing data between components in React using the
this.props.children technique with an example. [UN]
The this.props.children technique in React allows components to pass data
between parent and child components by embedding child elements within the
parent component's JSX code. It provides a way to access and render the content of
child components directly from the parent component.
Sample Code:
// ParentComponent.js
import React from 'react';

class ParentComponent extends React.Component {


render() {
return (
<div>
{/* Other content in the parent component */}
<ChildComponent>Hello from Child Component!</ChildComponent>
</div>
);
}
}

77
// ChildComponent.js
import React from 'react';

class ChildComponent extends React.Component {


render() {
return (
<div>
<p>{this.props.children}</p>
</div>
);
}
}

export default ParentComponent;

In this example, the ParentComponent wraps the ChildComponent, passing


the text "Hello from Child Component!" as the this.props.children. The
ChildComponent accesses and renders this content within its own JSX code,
displaying the message inside a <p> element.

10. Discuss the process of hydrate in React and its significance in the context of
server-side rendering. [UN]
Hydrate is a process in React that attaches event handlers and makes the
page interactive after server-side rendering. When React renders the page on the
server, it generates pure HTML markup without any JavaScript code or event
handlers. To enable interactivity, React needs to take control of the rendered page on
the client-side. This is done by including the necessary JavaScript bundles, such as
React and the application code, in the served page.

To achieve this, the ReactDOM.hydrate() method is used instead of the


traditional ReactDOM.render() method. Hydrate attaches event handlers to the server
-rendered DOM, allowing user interactions to work as expected.

Here are the steps involved in the hydrate process:


 Server-side rendering generates pure HTML markup without event handlers or
JavaScript code.
 The server includes the necessary JavaScript bundles, such as React and the
application code, in the template.
 When the page is loaded in the browser, the JavaScript bundles are fetched and
executed.
 ReactDOM.hydrate() is called with the routed page as the root element, attaching
event handlers to the server-rendered DOM.
 The page becomes interactive, and user interactions, such as clicking buttons or
navigating through routes using React Router, work as intended.

Hydrate ensures that the page retains its interactivity and provides a smooth user
experience after server-side rendering.

78
11. Build the ReactJs application that display Welcome message. [CR]
Below is a detailed step-by-step procedure to create the application:
Prerequisites:
 Node.js and npm installed on your computer. You can download them from
the official website: https://nodejs.org/

Step 1: Set Up the Project


 Open your terminal or command prompt.
 Create a new directory for your project and navigate to it:
mkdir react-welcome-app
cd react-welcome-app

Step 2: Initialize the Project


 Run the following command to create a new React project using Create React
App:
npx create-react-app .
79
The dot (.) at the end of the command specifies the current directory as the
project root.
Step 3: Code the Welcome Component
 Open the project in your preferred code editor (e.g., Visual Studio Code).
 In the "src" folder, you will find a file called "App.js." Open it.
 Replace the entire content of "App.js" with the following code:
import React from 'react';

function Welcome() {
return (
<div>
<h1>Welcome to My React App!</h1>
</div>
);
}
export default Welcome;

Step 4: Update the App Component to Render the Welcome Component


 In the same "src" folder, open the "App.js" file again.
 Modify the "App" component to render the "Welcome" component:
import React from 'react';
import Welcome from './Welcome';

function App() {
return (
<div>
<Welcome />
</div>
);
}

export default App;

Step 5: Start the Development Server


 Save all the changes in your code editor.
 In the terminal, while still in the project root directory, run the following
command to start the development server:
npm start

Your default web browser should open automatically, and you should see the
welcome message displayed on the screen.

12. Explain the functional and class components in React. [UN]


In React, there are two primary ways to create components: functional
components and class components. Both serve the same purpose of defining
reusable and modular UI elements, but they have different syntax and behavior. Let's
explore each type of component:

Functional Components:
80
Functional components are the simplest form of components in React. They
are essentially JavaScript functions that receive props as input and return JSX
(JavaScript XML) to define the component's UI. Here's an example of a functional
component:

import React from 'react';


function FunctionalComponent(props) {
return (
<div>
<h1>Hello, {props.name}!</h1>
</div>
);
}

Explanation:
 The import React from 'react'; statement is required for using JSX and React
features within the component.
 The FunctionalComponent is a JavaScript function that takes props as its
parameter.
 The component returns JSX, in this case, a <div> containing an <h1> tag with
a welcome message and the value of the name prop.

Functional Component Advantages:


 Simplicity: They are easy to write and understand.
 Performance: Functional components are lightweight and often faster than
class components.
 No state: Since functional components don't manage state, they promote a
clearer separation of concerns.

Class Components:
Class components are based on ES6 classes and provide additional features
compared to functional components. They have a more complex syntax and can
handle state, lifecycle methods, and more. Here's an example of a class component:
import React from 'react';

class ClassComponent extends React.Component {


constructor(props) {
super(props);
this.state = {
count: 0,
};
}
handleIncrement = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
81
<button onClick={this.handleIncrement}>Increment</button>
</div>
);
}
}

Explanation:
 The import React from 'react'; statement is required for using React features.
 The ClassComponent extends React.Component, making it a class-based
component.
 The constructor sets the initial state with a property called count.
 The handleIncrement method updates the state when the button is clicked.
 The render method returns JSX, displaying the current count and a button that
calls the handleIncrement method on click.

Class Component Advantages:


 State management: Class components can manage state using the state
object, allowing dynamic UI updates.
 Lifecycle methods: Class components have lifecycle methods like
componentDidMount, componentDidUpdate, and more, which can be useful
for side effects and data fetching.
 Refs: Class components can use refs to get references to DOM elements.

13. Design a web application of your choice to demonstrate the webpack and
modularization concept. [CR]
Let's design a simple web application for a To-Do List, where users can add,
edit, and delete tasks. We will use Webpack and modularization concepts to
organize the code into separate modules and bundle them using Webpack. This will
help us better manage the codebase and improve the application's performance.

Step 1: Set Up the Project


 Create a new project directory and navigate to it:
mkdir todo-list-app
cd todo-list-app

 Initialize a new Node.js project by running:


npm init -y

 Install necessary dependencies:


npm install webpack webpack-cli webpack-dev-server html-webpack-
plugin --save-dev
npm install react react-dom --save
npm install @babel/core @babel/preset-env @babel/preset-react babel
-loader --save-dev
npm install style-loader css-loader --save-dev

Step 2: Project Structure


 Create the following folder structure in your project directory:
82
todo-list-app
|-- src
| |-- index.js
| |-- components
| | |-- TodoList.js
| | |-- TodoItem.js
| |-- styles
| | |-- style.css
|-- webpack.config.js
|-- index.html

Step 3: Create the Components


 Inside the components folder, create two files: TodoList.js and TodoItem.js.
 In TodoList.js, create the TodoList component:
import React from 'react';
import TodoItem from './TodoItem';
const TodoList = ({ tasks, deleteTask }) => {
return (
<ul>
{tasks.map((task) => (
<TodoItem key={task.id} task={task} deleteTask={deleteTask} />
))}
</ul>
);
};
export default TodoList;
 In TodoItem.js, create the TodoItem component:
import React from 'react';
const TodoItem = ({ task, deleteTask }) => {
return (
<li>
{task.text}
<button onClick={() => deleteTask(task.id)}>Delete</button>
</li>
);
};
export default TodoItem;
Step 4: Create the Index File
 In the src folder, create index.js with the following code:
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import TodoList from './components/TodoList';
import './styles/style.css';
const App = () => {
const [tasks, setTasks] = useState([
{ id: 1, text: 'Learn React' },
{ id: 2, text: 'Build a To-Do List' },
]);

83
const deleteTask = (taskId) => {
setTasks(tasks.filter((task) => task.id !== taskId));
};
return (
<div>
<h1>To-Do List</h1>
<TodoList tasks={tasks} deleteTask={deleteTask} />
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));

Step 5: Create the HTML File


 Create index.html in the project root with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>To-Do List</title>
</head>
<body>
<div id="root"></div>
</body>
</html>

Step 6: Configure Webpack


 Create webpack.config.js in the project root with the following configuration:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
},
},
},
84
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html',
}),
],
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3000,
},
};

Step 7: Build and Run the Application


 Build the application by running the following command:
npx webpack
 Start the development server by running:
npx webpack serve
 Visit http://localhost:3000 in your web browser to see the To-Do List
application in action.

14. What is server side rendering and also give the advantages and disadvantages
of server side rendering? [RE]
Server-Side Rendering (SSR) is a technique used in web development where
the server generates the initial HTML content for a web page and sends it to the
client (web browser) to be displayed. In SSR, the server processes the request,
fetches data, and renders the entire page on the server side before sending it to the
client.

Advantages of Server-Side Rendering:


 Improved SEO: Search engines can crawl and index the fully rendered content,
as it is directly available in the HTML response. This can lead to better search
engine rankings and improved discoverability of your web pages.
 Faster Time-to-Content: Since the server sends a fully rendered page to the
client, users can see the content sooner, reducing the time it takes for the first
meaningful paint and improving perceived performance.
 Better User Experience: SSR helps reduce the time between the initial request
and the first content displayed, which leads to a smoother and more engaging
user experience.
 Accessibility: SSR ensures that the content is available to all users, including
those using browsers that may not support certain client-side JavaScript
features.
 Security: SSR can be advantageous for sensitive data that should not be
exposed to the client side, as the server can control what content is included
85
in the initial response.

Disadvantages of Server-Side Rendering:


 Increased Server Load: Since the server is responsible for rendering each
request, SSR can put a heavier load on the server, especially in scenarios with
a large number of concurrent users.
 Slower Navigation: Although SSR improves time-to-content for the initial
request, navigating between pages may be slower compared to client-side
rendering (CSR) because each page requires a new request to the server.
 Complexity: Implementing SSR can be more complex than CSR, as it requires
a server-side setup, which may involve additional considerations such as
server-side caching and managing data flow.

 Limited Client-Side Interactivity: With SSR, some client-side interactivity may


be limited during the initial load, as the full JavaScript bundle might not be
available until the page is hydrated on the client side.
 Development Challenges: SSR may require developers to consider both server
-side and client-side concerns, leading to a more complex development
process.

When to Use Server-Side Rendering:


 Use SSR when SEO is a crucial concern, and you want your content to be
easily discoverable by search engines.
 Consider SSR for pages that require fast time-to-content to improve user
experience and engagement.
 Utilize SSR for applications that serve sensitive data, as it offers better control
over initial content rendering.

When to Avoid Server-Side Rendering:


 If your application has a lot of client-side interactivity and navigation between
pages is frequent, client-side rendering (CSR) or a hybrid approach might be
more suitable.
 For applications with limited server resources or very high traffic, SSR might
not be the best choice due to the increased server load.

15. Summarize REST API.


A REST API (Representational State Transfer Application Programming
Interface) is a set of rules and conventions used to build web services that allow
different software applications to communicate with each other over the internet.
REST APIs follow the principles of the REST architectural style, which emphasizes
stateless, uniform, and resource-based communication. REST APIs are widely used
for building web and mobile applications, as they provide a standardized way to
interact with server resources.

Endpoint:
An endpoint is a specific URL (Uniform Resource Locator) on a web server
that is used to interact with a particular resource or perform a specific action. In the
context of RESTful APIs, each endpoint represents a resource, and different HTTP

86
methods are used to perform different actions on that resource. For example:
 https://api.example.com/users: This endpoint may be used to access a
collection of users' data.
 https://api.example.com/products/123: This endpoint may be used to access
details of a specific product with the ID "123".

Method:
In the context of web APIs, the method refers to the HTTP verb or action used
to interact with the endpoint and perform a specific operation on the resource. The
most common HTTP methods used in APIs are:
 GET: Used to retrieve data from the server.
 POST: Used to send data to the server to create a new resource.
 PUT: Used to update an existing resource on the server.
 DELETE: Used to remove a resource from the server.
The method used in an API request indicates the action the client wants to
perform on the resource associated with the endpoint.
Headers:
HTTP headers are additional pieces of information sent along with an HTTP
request or response. They provide metadata about the request or response and are
used to communicate various details between the client and the server. Some
common headers used in API requests include:
 Content-Type: Specifies the format of the data being sent in the request body
(e.g., application/json for JSON data).
 Authorization: Used to send authentication credentials with the request for
secure endpoints.
 User-Agent: Provides information about the client making the request (e.g.,
the web browser or client application).
Headers allow the client and server to exchange additional information necessary for
processing the request or response properly.

Data:
Data refers to the information sent as part of the API request or received as
part of the API response. The data can be in various formats, such as JSON, XML,
form data, or plain text, depending on the Content-Type specified in the request
headers.
For example, when making a POST request to create a new user, the client
sends data in the request body containing the user's information in a specific format,
like JSON:
{
"name": "John Doe",
"email": "[email protected]",
"age": 30
}
Advantages of REST APIs:
 Scalability: REST APIs are designed to be scalable, making them suitable for
handling large-scale applications with high traffic.
 Simplicity and Uniformity: REST APIs use standard HTTP methods and follow
a resource-based approach, making them easy to understand and implement.

87
 Platform Independence: Since REST APIs use standard HTTP methods and
data formats like JSON, they can be consumed by various platforms and
programming languages.
 Caching: REST APIs can leverage caching mechanisms to improve
performance and reduce server load.
 Security: REST APIs can use various security mechanisms, such as OAuth, to
secure data transmissions and protect resources.

Disadvantages of REST APIs:


 Over-fetching or Under-fetching: Clients may sometimes receive more or less
data than needed, leading to inefficient data usage.
 Versioning: Changing the structure of a resource in REST APIs may require
versioning to avoid breaking existing clients.
 Complexity for Complex Actions: Implementing complex actions or
workflows may require multiple requests, increasing complexity.

==>X<==

88

You might also like