0% found this document useful (0 votes)
7 views44 pages

Smart Training Resources India Private Limited, Chennai Fullstack Development Part-I Question Bank Questions in CSS

The document is a question bank for Fullstack Development, focusing on CSS and HTML topics. It covers various concepts such as CSS properties, selectors, layout techniques, semantic HTML, and the structure of HTML documents. Each section includes explanations, examples, and comparisons to help understand the fundamental aspects of web development.

Uploaded by

SUBHASISH BEHERA
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)
7 views44 pages

Smart Training Resources India Private Limited, Chennai Fullstack Development Part-I Question Bank Questions in CSS

The document is a question bank for Fullstack Development, focusing on CSS and HTML topics. It covers various concepts such as CSS properties, selectors, layout techniques, semantic HTML, and the structure of HTML documents. Each section includes explanations, examples, and comparisons to help understand the fundamental aspects of web development.

Uploaded by

SUBHASISH BEHERA
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/ 44

Smart Training Resources India Private Limited,Chennai

Fullstack Development Part-I

Question Bank

Questions in CSS:

1. What is the CSS float property used for?

The float property is used to position elements to the left or right within their container, allowing
other content to wrap around them. It is commonly used for layout purposes (e.g., text wrapping
around an image).
img { float: left; margin-right: 10px;

2. What is the purpose of the box-sizing property in CSS?

The box-sizing property controls how the total width and height of an element are
calculated.

a. content-box (default): Width and height apply only to the content, padding and
border are added outside.
b. border-box: Width and height include padding and border, making it easier to
manage layout sizes.
3. Can you explain and compare the concepts of margin and padding in CSS, highlighting their
differences and practical uses?
 Margin is the space outside an element's border, creating distance between it and
adjacent elements. It is used to control the spacing between elements.
 Padding is the space between an element's content and its border, used to add
space within an element.
 Differences: Margin controls external spacing, while padding controls internal
spacing.
Example:
div { padding: 20px; margin: 10px; }

4. What is the difference between position: relative and position: absolute in CSS?

 relative: The element is positioned relative to its normal position in the document flow.
It can be shifted using top, left, right, and bottom.
 absolute: The element is positioned relative to the nearest positioned ancestor (not
static) or the viewport if none exists
5. Identify and describe the different types of CSS selectors and explain their purpose in styling
HTML elements?


Universal Selector (*): Targets all elements on the page.

Type Selector (element): Targets elements of a specific type, e.g., div, p.

Class Selector (.class): Targets elements with a specific class

.ID Selector (#id): Targets an element with a specific ID.

Attribute Selector ([attribute]): Targets elements with a specific attribute.

Pseudo-classes (:hover, :first-child): Target elements based on their state or
position in the DOM
6. Discuss the use of CSS pseudo-classes and pseudo-elements. Explain the difference between
them, and provide examples of their use in styling interactive elements like links, buttons, and
form fields.
 Pseudo-classes: Used to define the special state of an element, like when it is hovered
over, focused, or visited.
o Examples: :hover, :focus, :nth-child(), :active.
 Pseudo-elements: Used to style specific parts of an element, such as the first letter or
line of text, or to insert content before or after an element.
o Examples: ::before, ::after, ::first-letter, ::first-line.

Examples:

/* Pseudo-class: hover */
a:hover {
color: red;
}

/* Pseudo-element: first letter */


p::first-letter {
font-size: 2em;
font-weight: bold;
}

7. Explain what is CSS transition and CSS animation? Explain the difference between them.Provide
an example for both?.

 CSS Transitions: Used to create smooth transitions between property values when an
element's state changes (e.g., hover). Transitions are triggered by events like hover or focus.
o Key properties: transition-property, transition-duration, transition-timing-
function.
 CSS Animations: Provide more control than transitions and can run continuously or infinitely.
Animations are defined with keyframes and can involve more complex sequences of
changes.
o Key properties: @keyframes, animation-name, animation-duration, animation-
timing-function.

Example - Transition:

button {
background-color: blue;
color: white;
transition: background-color 0.3s ease-in-out;
}

button:hover {
background-color: green;
}

Example - Animation:

@keyframes move {
0% { left: 0; }
100% { left: 100px; }
}

div {
position: relative;
animation: move 2s infinite;
}

8. Discuss the differences between Flexbox and CSS Grid. When would you choose one over the
other? Provide examples of layout scenarios where Flexbox or CSS Grid would be the best
solution.

 Flexbox: A one-dimensional layout system (can align items in a row or column). Flexbox is
useful for simple layouts where elements need to be distributed evenly or aligned within a
single row or column.
o Use Flexbox for aligning items, distributing space between them, or creating simple
navigation bars.
 CSS Grid: A two-dimensional layout system (can align items both in rows and columns). CSS
Grid is better for complex layouts where you need precise control over both rows and
columns simultaneously.
o Use CSS Grid for multi-column and multi-row layouts like full-page grids, media
galleries, or complex page structures.

Examples:

Flexbox Example (simple horizontal navigation bar):

.nav {
display: flex;
justify-content: space-around;
}

Grid Example (two-column layout):

.container {
display: grid;
grid-template-columns: 1fr 3fr;
grid-gap: 20px;
}

9. Explain the CSS Box Model in detail. Discuss how padding, margin, border, and content affect
the layout of a web page. Provide examples of how each component can be modified and how
the box-sizing property can change the behavior of the box model.

 The CSS Box Model defines the layout of elements on a web page, including content,
padding, border, and margin.
o Content: The actual content of the box, such as text or images.
o Padding: Space between the content and the border, affecting the element's
inner space.
o Border: Surrounds the padding, affecting the element's outer space.
o Margin: Space outside the border, separating the element from other
elements.
 The box-sizing property can change the way width and height are calculated:
o content-box (default): Width and height only affect the content area, not the
padding or border.
o border-box: Width and height include the padding and border, making it easier
to control the total size of an element.

Example:

div {
width: 200px;
padding: 10px;
border: 5px solid black;
margin: 20px;
box-sizing: border-box; /* includes padding and border in the width and height */
}

10. What is the purpose of the display property in CSS? Explain the different values of the display
property and how they affect the layout of elements. Provide examples of when to use block,
inline, inline-block, and none.

 display property: Defines how an element is displayed in the document flow. It is crucial
for controlling the layout of web pages.
 Different values of display:
o block: Elements take up the full width of their parent and start on a new line
(e.g., <div>, <p>).
o inline: Elements take up only as much width as necessary and do not start a
new line (e.g., <span>, <a>).
o inline-block: Elements behave like inline elements but allow width and height
properties.
o none: The element is not displayed at all (it is removed from the document
flow).

Examples:

div {
display: block;
}

span {
display: inline;
}

button {
display: inline-block;
}

.hide {
display: none;
}
Smart Training Resources India Private Limited,Chennai

Fullstack Development Part-I

Question Bank

Questions in Html:

1. What is HTML?
HTML (HyperText Markup Language) is the standard language used for creating
webpages. It structures content on the web using tags to define elements like headings, paragraphs,
images, links, and more.
2. Distinguish between the <div> and <span> elements in HTML

<div> is a block-level element, used to group larger sections of content, while <span>
is an inline element, used for styling small portions of text or other inline content.

3. Recall the purpose of the <head> element in an HTML document?

The <head> element in an HTML document contains metadata about the document, such as
the title, links to stylesheets, scripts, and other resources. It does not display any content on the page
but is important for setting up the document's settings and resource

4. Illustrate the difference between block-level element and inline element in Html?
 Block-level elements: Take up the full width of the available space, starting on a new
line. They stack vertically.
Examples: <div>, <p>, <h1>, <section>
 Inline elements: Take up only as much width as necessary, and do not start on a new
line. They flow along with surrounding content.
Examples: <span>, <a>, <strong>, <em>

5. What are HTML tables? Explain how to create a table with rows, columns, and headings. Include an
example of a table with multiple rows and columns.

HTML tables display data in rows and columns. You define a table using the <table> tag, and
inside it, you use <tr> for rows, <th> for headings, and <td> for table data cells.

Example:

<table border="2" cellpadding="5" cellspacing="5" height="500" width="300" bordercolor="red"


bgcolor="yellow" style="border-collapse: collapse;">
<caption><b>Employees List</b></caption>
<thead>
<tr>
<td colspan="4" align="center">
<b>List of Employee Salaries</b>
</td>
</tr>
</thead>
<tr bgcolor="green">
<th>Name</th>
<th>Age</th>
<th>Place</th>
<th>Amount</th>
</tr>
<tr>
<td>Ashwin</td>
<td>23</td>
<td>Pune</td>
<td>
<table>
<tr>
<td>5000</td>
<td>5000</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>Rajkumar</td>
<td>25</td>
<td>Kolkata</td>
<td>15000</td>
</tr>
<tr>
<td>Keshav Rao</td>
<td>29</td>
<td rowspan="2">Cuttack</td>
<td>20000</td>
</tr>
<tr>
<td>John Smith</td>
<td>26</td>
<td>25000</td>
</tr>
<tr>
<td colspan="3"><b>Total Amount</b></td>
<td bgcolor="blue"><strong>70000</strong></td>
</tr>
<tfoot>
<tr>
<td colspan="4"><center>
<b>Rupees Seventy Thousand Only</b>
</center></td>
</tr>
</tfoot>
</table>
6. Explain the use of semantic HTML elements. Why are semantic elements important for SEO and
accessibility? Provide examples of semantic tags such as <header>, <footer>, <article>, <section>,
and <nav>.

Semantic HTML elements clearly describe their content, making the webpage more readable
for both humans and search engines. They improve SEO and accessibility by giving meaningful
structure.

 <header>: Represents the header of a section or page.


 <footer>: Represents the footer of a section or page.
 <article>: Represents independent content that could be reused.
 <section>: Represents a thematic grouping of content.
 <nav>: Represents a navigation block for links.
Example:

<header>
<h1>Welcome to My Website</h1>
</header>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
</ul>
</nav>
<section>
<h2>Article Heading</h2>
<p>This is an article.</p>
</section>
<footer>
<p>© 2025 My Website</p>
</footer>

7. Explain the concept and use of HTML metadata. What is the purpose of the <meta> tag, and how is
it used in web pages to improve search engine optimization (SEO) and specify document settings?

The <meta> tag provides metadata about the document. It’s used for character encoding, author
information, keywords for SEO, and viewport settings for responsive design.

 <meta charset="UTF-8">: Defines the character encoding.


 <meta name="description" content="Description of the page">: Provides a description for
search engines.
 <meta name="viewport" content="width=device-width, initial-scale=1.0">: Ensures proper
scaling on mobile devices.

Example:

<head>
<meta charset="UTF-8">
<meta name="description" content="A webpage for SEO examples">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SEO Page</title>
</head>

8. Explain the structure and essential elements of an HTML document. How do the <head> and
<body> sections differ in terms of content and functionality? Provide a detailed example of a
complete HTML page.

 The basic structure of an HTML document, including <!DOCTYPE html>, <html>, <head>, and
<body>.
 Differences between <head> and <body>, emphasizing that the <head> contains metadata,
while the <body> contains visible content

Example Answer:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sample HTML Page</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
</header>
<section>
<p>This is a paragraph of text that provides information about the content on the page.</p>
<a href="https://www.example.com">Visit Example</a>
</section>
<footer>
<p>© 2025 My Website</p>
</footer>
</body>
</html>

9. Explain with examples how to create forms with text fields, radio buttons, checkboxes, and submit
buttons.

<form action="/submit" method="POST">


<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>

<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br><br>

<label for="interests">Interests:</label>
<input type="checkbox" id="coding" name="interests" value="coding">
<label for="coding">Coding</label>
<input type="checkbox" id="music" name="interests" value="music">
<label for="music">Music</label><br><br>

<button type="submit">Submit</button>
</form>

10. Write an program on unordered list,ordered list and definition list with all attributes.?
<p>Unordered List</p>
<ul type="disc">
<li>Milk</li>
<li>Eggs</li>
<li>Bread</li>
<li>Fruits</li>
<li>Groceries</li>
</ul>
<p>Ordered List</p>
<ol type="a" start="6" reversed>
<li>Audi</li>
<li>Aston Martin</li>
<li>Lamborghini</li>
<li>BMW</li>
<li>Ferrari</li>
</ol>
<p>Definition List</p>
<dl>
<dt>Mercury:</dt>
<dd>It is a Liquid Metal.</dd>
</dl>
Smart Training Resources India Private Limited,Chennai

Fullstack Development Part-I

Question Bank

Questions in Javascript:

1. Define a variable in JavaScript and demonstrate the different ways to declare one?

A variable is a container for storing data values. You can declare a variable using:

 let (for mutable variables)


 const (for immutable variables)
 var (older way, function-scoped)

Example:

let x = 10;
const y = 20;

2. Explain what a function is in JavaScript, and demonstrate how to define one with an example?

A function is a block of reusable code that performs a task. You define it using the function keyword
or using arrow function syntax.

function greet() {
console.log("Hello, world!");
}

1. What are JavaScript data types? List the primitive data types in JavaScript.

JavaScript data types can be primitive or non-primitive. Primitive types include:

 String
 Number
 Boolean
 Undefined
 Null
 Symbol (introduced in ES6)
 BigInt (introduced in ES11)

2. Describe what a JavaScript event is and illustrate its usage with a practical example?

A JavaScript event is an action or occurrence that happens in the browser, such as a mouse click or a
key press. Example: click, keydown, load.

document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
3. Describe the concept of a callback function and its purpose in programming.

A callback function in JavaScript is a function that is passed as an argument to another function and is
executed after the completion of that function's task. It allows asynchronous operations like API calls,
timers, or events to happen without blocking the main execution flow.

Example:

<html>
<body>
<h2>Callback Function Example</h2>
<button id="changeTextButton">Change Text</button>
<div id="textContainer">Initial Text</div>
<script>
function changeText() {
const textContainer = document.getElementById("textContainer");
textContainer.textContent = "The text has been changed!";
}
function addClickEventListener(buttonId, callback) {
const button = document.getElementById(buttonId);
button.addEventListener("click", callback);
}
addClickEventListener("changeTextButton", changeText);
</script>
</body
</html>

4. Explain the concept of closures in JavaScript. How do closures work and provide an example where
closures can be useful?

A closure in JavaScript is a function that retains access to its lexical scope, even after the function has
finished execution. This means that a function can "remember" the environment in which it was
created, including variables and parameters, even if the outer function has completed its execution.

How Closures Work:

When a function is defined inside another function, it has access to the variables of the outer
function. This is a closure.

Example:
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}

const increment = outer();


increment(); // 1
increment(); // 2
Here, inner() has access to the count variable from outer(), even after outer() has finished executing.

Usefulness:

Closures are useful for creating data privacy (encapsulation) and for situations where you need to
maintain state between function calls (like in event handlers or timers).

5. Design a JavaScript function that uses Promises to handle multiple asynchronous tasks, and
describe how you would structure it.

A Promise in JavaScript represents an operation that is not yet complete but will be resolved in the
future. It can be in one of three states:

1. Pending: The initial state, neither fulfilled nor rejected.


2. Fulfilled: The operation completed successfully.
3. Rejected: The operation failed.

Example:
<html>
<body>
<h2>Promise Example</h2>
<p id="message">Waiting for data...</p>

<script>
function fetchData() {
return new Promise((resolve, reject) => {
let success = true;
setTimeout(() => {
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Failed to fetch data!");
}
}, 2000);
});
}
fetchData()
.then((message) => {
document.getElementById("message").textContent = message;
})
.catch((error) => {
document.getElementById("message").textContent = error;
});
</script>
</body>
</html>
6. Explain the concept of hoisting in JavaScript. How does hoisting work with variables and functions?
Provide examples to demonstrate how hoisting affects code execution.

Hoisting is JavaScript's default behaviour of moving declarations to the top of the current scope
before code execution. This applies to variables and functions.

 Function Hoisting: Entire function declarations are hoisted.

foo(); // "Hello!"
function foo() {
console.log("Hello!");
}

 Variable Hoisting: var declarations are hoisted but initialized with undefined. let and const
declarations are hoisted but not initialized, resulting in a "Temporal Dead Zone".

console.log(a); // undefined
var a = 5;

7. What are JavaScript's higher-order functions? Discuss common higher-order functions like map(),
filter(), and reduce(), and provide examples of each.

Higher-order functions are functions that take one or more functions as arguments or return a
function as a result.

Examples:

1. map(): Creates a new array populated with the results of calling a provided function on every
element in the calling array.

let numbers = [1, 2, 3];


let squared = numbers.map(num => num * num); // [1, 4, 9]

2. filter(): Creates a new array with all elements that pass the test implemented by the
provided function.

let numbers = [1, 2, 3, 4, 5];


let evenNumbers = numbers.filter(num => num % 2 === 0); // [2, 4]

3. reduce(): Applies a function against an accumulator and each element in the array to reduce
it to a single value.

let numbers = [1, 2, 3];


let sum = numbers.reduce((acc, num) => acc + num, 0); // 6

8. Explain the concept of asynchronous programming in JavaScript. How does the async/await syntax
simplify working with promises? Provide an example.

Asynchronous programming is a programming paradigm that allows tasks, such as I/O


operations, network requests, or timers, to be performed in the background while the rest
of the code continues executing. This is important for preventing blocking or freezing of
applications, especially in user interfaces or servers.
In JavaScript, asynchronous programming can be handled using Promises and async/await.

Basic Syntax:

async function fetchData() {


console.log("Fetching data...");

await new Promise(resolve => setTimeout(resolve, 2000));

console.log("Data fetched!");
}
fetchData();
Example:
<html>
</head>
<body>
<h2>Asynchronous Task Result</h2>
<div id="output"></div>

<script>
function fetchData() {
return new Promise((resolve, reject) => {
let success = true;

setTimeout(() => {
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Error: Data fetch failed.");
}
}, 2000);
});
}
async function getData() {
try {
const result = await fetchData();
document.getElementById("output").innerText = result;
} catch (error) {
document.getElementById("output").innerText = error;
}
}

getData();
</script>

</body>
</html>
Smart Training Resources India Private Limited,Chennai

Fullstack Development Part-I

Question Bank

Questions in ReactJS:
1. What is ReactJS and why is it widely used in web development?

Ans. ReactJS is a JavaScript library for building dynamic user interfaces using reusable components. It is
widely used because its component-based architecture, virtual DOM, and unidirectional data flow help
create fast, maintainable, and scalable web applications.

2. What is JSX, and how does it relate to JavaScript?

Ans. JSX (JavaScript XML) is a syntax extension that allows you to write HTML-like code within JavaScript. It
is transpiled into standard JavaScript, making UI code more readable and easier to maintain.

3. Explain the concept of props in React.

Ans. Props (short for properties) are read-only inputs passed from parent to child components. They
enable data flow and configuration of components, making them reusable and dynamic.

4. How does the useEffect Hook function in managing side effects?

Ans. The useEffect hook runs after the component renders. It takes a function to perform side effects such
as data fetching or subscriptions, and an optional dependency array to control when the effect re-runs.

5. Describe the Virtual DOM in React.

Ans. The virtual DOM is a lightweight, in-memory representation of the actual DOM. When a component’s
state or props change, React creates a new virtual DOM tree and compares it to the previous version using
a diffing algorithm.
This process, known as reconciliation, identifies exactly what has changed, and React then updates only
those specific parts of the real DOM. This minimizes costly direct DOM manipulations and greatly
improves performance, particularly in large, dynamic applications.
In summary, the virtual DOM allows React to optimize rendering by reducing unnecessary updates,
resulting in a faster and more responsive UI.

6. Discuss state management in React applications.

Ans. State in React represents dynamic data that influences what gets rendered. Local component state
can be managed using:

 Class Components: via this.state and this.setState.


 Functional Components: via the useState Hook, which returns the current state and an
updater function.
For larger or more complex applications, global state management strategies can be
employed using the Context API, Redux, or MobX. These tools help share state across
multiple components without cumbersome prop drilling.
Each method has its own trade-offs:
 Local State: Simple and encapsulated, best for isolated component data.
 Global State: Useful for sharing data across many components, though it may add
complexity.
Overall, choosing the right state management approach depends on the app’s size, data
flow complexity, and maintenance requirements.

7. Differentiate between controlled and uncontrolled components in React.


Ans. A controlled component is one in which form data (such as the value of an input field) is handled by
React state. In these components, every change triggers an onChange event that updates the state,
ensuring that the UI is always in sync with the state.

Uncontrolled components, however, maintain their own internal state. Data is accessed using refs,
meaning that the DOM itself is the source of truth.

Controlled components provide easier data validation and state synchronization, while uncontrolled
components are simpler to set up for simple use cases but offer less control over user input.

8. Create a simple counter app that increases/decreases the count by 1. What is useState hook in
react? What are the advantages of using hooks? (5+2+3)

Ans.

The useState hook is a built-in function in React that lets functional components manage local state. It
takes an initial value as its argument and returns an array with two elements: the current state value and a
function to update that state. When you call the update function, React re-renders the component with
the new state. This hook replaces the need for class-based state management using this.state and
this.setState, making state management in functional components straightforward.

Hooks offer several key advantages in React applications:

 Simpler Code & Less Boilerplate: Hooks allow you to use state and other React features in functional
components without the need for class components and manual binding of methods.
 Enhanced Reusability: With custom hooks, you can extract and reuse stateful logic across different
components.
 Improved Readability and Maintainability: Hooks lead to cleaner, more modular code, making it
easier to manage component logic and side effects.

9. What is a state in ReactJS? How do you handle events in React applications? What is useRef Hook
and why is it used in React? Give two examples of React Hooks with their functions. How to install
libraries? Alternatively how to install libraries with a specific version?(2+2+2+2+1+1)

Ans. State is an object managed within a component that holds dynamic data. When state changes (using
setState or useState), React re-renders the component, allowing the UI to update interactively.

In React, events are handled by assigning event handler functions (using camelCase names) as props to JSX
elements. These handlers receive a synthetic event object that normalizes browser differences, ensuring
consistent behavior.
The useRef hook creates a mutable reference that persists across renders. It’s commonly used to access or
store a reference to a DOM element and to hold mutable values without causing re-renders.

Two examples of React Hooks:

 useState: Manages local state within functional components.


 useEffect: Executes side effects (like data fetching) after rendering and updates when specified
dependencies change.

To install:

 Library with the latest version: npm install react


 Library with the specific version: npm install [email protected]

10. Difference between Functional Components and Class Components?

Functional Components Class Components


A functional component is just a plain JavaScript pure A class component requires you to extend from React.
function that accepts props as an argument and Component and create a render function that returns a
returns a React element(JSX). React element.
There is no render method used in functional It must have the render() method returning JSX (which
components. is syntactically similar to HTML)
The class component is instantiated and different life
Functional components run from top to bottom and
cycle method is kept alive and is run and invoked
once the function is returned it can’t be kept alive.
depending on the phase of the class component.
Also known as Stateless components as they simply
Also known as Stateful components because they
accept data and display them in some form, they are
implement logic and state.
mainly responsible for rendering UI.
React lifecycle methods (for example,
React lifecycle methods can be used inside class
componentDidMount) cannot be used in functional
components (for example, componentDidMount).
components.
Smart Training Resources India Private Limited,Chennai

Full Stack Development Part-2

Question Bank on Angular


2 Mark Questions & Answers:

1. Explain the purpose of the `@Component` decorator in Angular?

The `@Component` decorator in Angular is used to define a component. It


provides metadata about the component, such as its selector, template URL, and styles,
allowing Angular to understand how to instantiate and render the component.

2. Define data binding in Angular?

Data binding in Angular is the mechanism that allows synchronization between


the model (data) and the view (UI). Angular supports two-way data binding, where
changes in the model automatically update the view and vice versa, as well as one-way
data binding for unidirectional data flow.

3. Illustrate routing in Angular and why it is useful in creating single page


application?

Routing in Angular allows navigation between different views or components


within a single-page application. The Angular Router enables developers to define
routes, manage navigation, and load components dynamically based on the URL.

4. Recall the purpose of the `ngFor` directive?

The `ngFor` directive in Angular is used to iterate over a collection (like an array)
and render a template for each item in the collection. It is commonly used to create lists
or tables dynamically based on data.

5 Mark Questions & Answers:

1. Describe Angular routing and how to implement navigation between


components.

Angular routing enables navigation between different views (components)


within a single-page application (SPA).12

 Routing Module:
o A dedicated module (e.g., app-routing.module.ts) is used to configure
routes.
o The RouterModule is used to define and manage routes.
 Routes Definition:
o Routes are defined as an array of objects, where each object specifies a
path and the corresponding component.
 Router Outlet:
o The <router-outlet> directive is used in the template to indicate where
the routed component should be displayed.
 Navigation:
o Navigation can be performed using the routerLink directive in templates
or the Router service in component code.

Example:

TypeScript
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [


{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}

// app.component.html
<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>

2. Distinguish Angular forms (template-driven and reactive) and their


differences.

Feature Template-Driven Forms Reactive Forms


Built using Angular directives in Built programmatically using
Definition
the template. FormGroup and FormControl.
Form Model Implicitly created based on the Explicitly defined in the component
Creation template. class.
Uses directives in the template Defined in the component using
Validation
(e.g., required). Validators.
Explicit data flow, controlled via
Data Flow Automatic two-way data binding.
observables.
Feature Template-Driven Forms Reactive Forms
More challenging due to implicit Easier to test due to explicit form
Testing
nature. model.
Best for simple forms with Ideal for complex forms with
Use Cases
minimal complexity. dynamic validation and interactions.
Example Uses formControlName and
Uses ngModel directive.
Syntax formGroup.
Differences:
 Template-driven forms are easier for simple forms, while reactive forms are
better for complex forms.
 Reactive forms offer more control over form logic and validation.
 Reactive forms are more testable.
 Template driven uses two way data binding with ngModel. Reactive forms uses
one way data binding with formControlName.

3. Explain the component-based architecture of Angular.

Angular follows a component-based architecture, which is a design paradigm that


emphasizes the use of reusable components to build user interfaces. Each component in
Angular encapsulates its own view (HTML template), behavior (TypeScript class), and
styles (CSS).

1. Encapsulation: Components promote encapsulation by bundling the template,


logic, and styles together, making it easier to manage and maintain code. This
modular approach allows developers to create self-contained units of
functionality.
2. Reusability: Components can be reused across different parts of an application
or even in different applications. This reduces code duplication and enhances
maintainability.
3. Hierarchy: Components can be nested within other components, forming a tree
structure. This hierarchy allows for complex UIs to be built from simple building
blocks, making it easier to manage state and data flow.
4. Data Binding: Angular components support data binding, which allows for
synchronization between the model and the view. This means that changes in the
model automatically reflect in the view and vice versa, enhancing user
experience.
5. Lifecycle Hooks: Angular components have lifecycle hooks (e.g., ngOnInit,
ngOnDestroy) that allow developers to tap into key events in a component's
lifecycle, enabling better resource management and initialization logic.

4. Describe Angular pipes and how to create a custom pipe. Provide an example.

Angular pipes are used to transform data in templates before displaying it to the user.1
They take input data, process it, and return the transformed output.2 Angular provides built-in
pipes (e.g., DatePipe, UpperCasePipe), and developers can create custom pipes for specific
data transformations.

 Purpose:
o Data formatting and transformation.3
o Improving template readability.
o Reusability of transformation logic.
 Creating a Custom Pipe:
1. Generate a pipe using the Angular CLI: ng generate pipe my-custom
2. Implement the PipeTransform interface in the generated pipe class.
3. Define the transform() method, which takes the input value and optional
parameters, and returns the transformed value.
 Example:

// my-custom.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'myCustom',
})
export class MyCustomPipe implements PipeTransform {
transform(value: string, limit: number): string {
if (!value) return '';
if (value.length > limit) {
return value.substring(0, limit) + '...';
}
return value;
}
}

// my.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-my',
template: `<p>{{ longText | myCustom: 10 }}</p>`,
})
export class MyComponent {
longText = 'This is a very long text string.';
}

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MyComponent } from './my.component';
import { MyCustomPipe } from './my-custom.pipe';

@NgModule({
declarations: [MyComponent, MyCustomPipe],
imports: [BrowserModule],
bootstrap: [MyComponent],
})
export class AppModule {}
In this example, myCustom pipe truncates a string to a specified limit and adds "..." if
it exceeds the limit.

10 Mark Questions and Answers:

1. Create A Dropdown Menu using ngSwitch Directives in Angular.

we will create a simple Angular application that uses ngSwitch to display different
messages based on the selected option from a dropdown menu.

Step 1: Set Up the Angular Application

If you haven't already set up an Angular application, you can create one using the
Angular CLI:

ng new ngSwitchExample
cd ngSwitchExample
npm start

Step 2: Create the Component

1. Generate a new component (if you want to keep it organized):

ng generate component switch-example

2. Update the component's TypeScript file (switch-example.component.ts):

import { Component } from '@angular/core';

@Component({
selector: 'app-switch-example',
templateUrl: './switch-example.component.html',
styleUrls: ['./switch-example.component.css']
})
export class SwitchExampleComponent {
selectedOption: string = 'option1'; // Default option

// Options for the dropdown


options = [
{ value: 'option1', label: 'Option 1' },
{ value: 'option2', label: 'Option 2' },
{ value: 'option3', label: 'Option 3' }
];
}

Step 3: Create the Template

3. Update the component's HTML file (switch-example.component.html):


html
<div>
<h2>Select an Option</h2>
<select [(ngModel)]="selectedOption">
<option *ngFor="let option of options" [value]="option.value">{{ option.label
}}</option>
</select>

<div [ngSwitch]="selectedOption">
<div *ngSwitchCase="'option1'">
<p>You selected Option 1!</p>
</div>
<div *ngSwitchCase="'option2'">
<p>You selected Option 2!</p>
</div>
<div *ngSwitchCase="'option3'">
<p>You selected Option 3!</p>
</div>
<div *ngSwitchDefault>
<p>Please select an option.</p>
</div>
</div>
</div>

Step 4: Import FormsModule

4. Make sure to import FormsModule in your application module


(app.module.ts) to use ngModel for two-way data binding:

typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // Import FormsModule

import { AppComponent } from './app.component';


import { SwitchExampleComponent } from './switch-example/switch-
example.component';

@NgModule({
declarations: [
AppComponent,
SwitchExampleComponent
],
imports: [
BrowserModule,
FormsModule // Add FormsModule here
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Step 5: Use the Component in the App

5. Update the main application template (app.component.html) to include the


new component:

<app-switch-example></app-switch-example>

Step 6: Run the Application

6. Run the application:

npm start

Now, navigate to http://localhost:4200 in your browser. You should see a dropdown


menu with three options. When you select an option, the corresponding message will be
displayed below the dropdown based on the selected value using ngSwitch.

‘’’’’’’

2. Create and Design an Counter App to Increase, Decrease and Reset a Value
using data and event binding in Angular.

Steps to create and design this counter app.

Step 1: Set Up the Angular Application

If you haven't already set up an Angular application, you can create one using the
Angular CLI:

ng new counter-app
cd counter-app
npm start

Step 2: Create the Counter Component

1. Generate a new component for the counter:

ng generate component counter

Step 3: Update the Counter Component

2. Update the component's TypeScript file (counter.component.ts):

import { Component } from '@angular/core';

@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css']
})
export class CounterComponent {
count: number = 0; // Initialize the counter value

// Method to increase the counter


increase() {
this.count++;
}

// Method to decrease the counter


decrease() {
this.count--;
}

// Method to reset the counter


reset() {
this.count = 0;
}
}

Step 4: Create the Template

3. Update the component's HTML file (counter.component.html):

<div class="counter-container">
<h1>Counter App</h1>
<div class="counter-value">
<h2>{{ count }}</h2>
</div>
<div class="button-group">
<button (click)="increase()" class="btn">Increase</button>
<button (click)="decrease()" class="btn">Decrease</button>
<button (click)="reset()" class="btn">Reset</button>
</div>
</div>

Step 5: Add Some Basic Styles

4. Add styles to the component's CSS file (counter.component.css):

.counter-container {
text-align: center;
margin-top: 50px;
}

.counter-value {
font-size: 48px;
margin: 20px 0;
}

.button-group {
display: flex;
justify-content: center;
gap: 10px;
}

.btn {
padding: 10px 20px;
font-size: 18px;
cursor: pointer;
border: none;
border-radius: 5px;
background-color: #007bff;
color: white;
transition: background-color 0.3s;
}

.btn:hover {
background-color: #0056b3;
}

Step 6: Use the Counter Component in the App

5. Update the main application template (app.component.html) to include the


new counter component:

<app-counter></app-counter>

Step 7: Run the Application

6. Run the application:

npm start

Now, navigate to http://localhost:4200 in your browser. You should see a simple


counter application with buttons to increase, decrease, and reset the counter value.
Smart Training Resources India Private Limited,Chennai

Full Stack Development Part-2

Question Bank on ExpressJS


2 Mark Questions & Answers:

1. Enlighten middleware in Express.js?

Middleware in Express.js refers to functions that have access to the request and
response objects in the application’s request-response cycle. They can perform
operations such as modifying the request, ending the response, or calling the next
middleware function in the stack.

2. Illustrate the purpose of the `app.use()` method in Express.js?

The `app.use()` method in Express.js is used to mount middleware functions at a


specified path. It can be used for various purposes, such as logging requests, parsing
request bodies, or serving static files.

3. How can you handle errors in Express.js?

You can handle errors in Express.js by defining an error-handling middleware


function with four parameters: `err`, `req`, `res`, and `next`. This function can be used to
send error responses to the client. For example:

app.use((err, req, res, next) => {

res.status(500).send('Something broke!');});

4. Explain routing in Express.js?

Routing in Express.js refers to the mechanism of defining endpoints (routes) in


the application that respond to client requests. Each route can handle different HTTP
methods (GET, POST, etc.) and can be defined using methods like `app.get()`,
`app.post()`, etc.

5 Mark Questions & Answers:

1. Explain the concept of middleware in Express.js and provide examples of its


usage.

Middleware in Express.js refers to functions that execute during the request-


response cycle. They have access to the request object (`req`), the response object
(`res`), and the next middleware function in the stack (`next`). Middleware can perform
a variety of tasks, such as logging requests, modifying request and response objects,
handling errors, and serving static files.
Examples of Middleware Usage:

i. Logging Middleware:

app.use((req, res, next) => {

console.log(`${req.method} ${req.url}`);

next(); // Pass control to the next middleware

});

ii. Body Parsing Middleware:

const bodyParser = require('body-parser');

app.use(bodyParser.json()); // Parse JSON request bodies

iii. Error Handling Middleware:

app.use((err, req, res, next) => {

console.error(err.stack);

res.status(500).send('Something broke!');

});

Middleware is essential for building modular and maintainable applications in


Express.js.

2. Describe how routing works in Express.js and how to implement route


parameters.

Routing in Express.js is the mechanism that allows you to define endpoints


(routes) for your application that respond to client requests. Each route can handle
different HTTP methods (GET, POST, PUT, DELETE, etc.) and can be defined using
methods like `app.get()`, `app.post()`, etc.

Implementing Route Parameters:

Route parameters are named URL segments that can be used to capture values from the
URL. They are defined by a colon (:) followed by the parameter name.

Example:

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

const userId = req.params.userId; // Access the route parameter

res.send(`User ID is: ${userId}`);


})

In this example, if a client makes a GET request to `/users/123`, the response will be
"User ID is: 123". This allows for dynamic routing and handling of user-specific data.

3. How can you implement error handling in an Express.js application? Provide an


example.

Error handling in Express.js can be implemented using middleware functions


specifically designed to catch and handle errors. An error-handling middleware function
has four parameters: `err`, `req`, `res`, and `next`. This function can be used to send error
responses to the client.

Example of Error Handling:

// Route that may throw an error

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

try {

// Simulate an error

throw new Error('Data not found');

} catch (err) {

next(err); // Pass the error to the error-handling middleware

});

// Error-handling middleware

app.use((err, req, res, next) => {

console.error(err.stack); // Log the error stack

res.status(500).send('Something went wrong!'); // Send a generic error response

});

In this example, if an error occurs in the `/data` route, it is passed to the error-handling
middleware, which logs the error and sends a 500 status response to the client.

4. Illustrate how to serve static files in an Express.js application and provide an


example.
Serving static files in an Express.js application can be accomplished using the
built-in `express.static` middleware. This middleware allows you to specify a directory
from which static files (like HTML, CSS, JavaScript, images, etc.) can be served.

Example of Serving Static Files:

1. First, create a directory named `public` and place your static files (e.g., `index.html`,
`style.css`) inside it.

2. Use the following code to serve the static files:

const express = require('express');

const app = express();

// Serve static files from the 'public' directory

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

app.listen(3000, () => {

console.log('Server is running on port 3000');

});

In this example, if you place an `index.html` file in the `public` directory, it can be
accessed directly via `http://localhost:3000/index.html`. This makes it easy to serve
front-end assets alongside your Express.js application.

10 Mark Questions and Answers:

1. Explain the architecture of an Express.js application and describe its key


components.

The architecture of an Express.js application is built around the concept of


middleware and routing, which allows for a modular and scalable design. The key
components of an Express.js application include:

 Application Object (`app`): The core of an Express application, created using


`express()`. It is used to configure middleware, define routes, and start the
server.
 Middleware: Functions that execute during the request-response cycle.
Middleware can perform tasks such as logging, authentication, parsing request
bodies, and handling errors. Middleware can be global (applied to all routes) or
route-specific.
 Routing: The mechanism for defining endpoints that respond to client requests.
Routes can be defined for different HTTP methods (GET, POST, PUT, DELETE)
and can include route parameters and query strings.
 Request and Response Objects: The `req` (request) and `res` (response)
objects are passed to middleware and route handlers. The `req` object contains
information about the incoming request, while the `res` object is used to send
responses back to the client.
 Error Handling: Express provides a way to handle errors through error-
handling middleware. This middleware can catch errors that occur during
request processing and send appropriate responses.
 Static Files: Express can serve static files (HTML, CSS, JavaScript, images) using
the `express.static` middleware, allowing for easy integration of front-end assets.
 Server: The application can be run on a server using the `app.listen()` method,
which binds the application to a specific port and starts listening for incoming
requests.

Overall, the architecture of an Express.js application promotes separation of concerns,


making it easier to manage and scale applications.

2. Describe how to implement RESTful APIs using Express.js. Include examples of


CRUD operations.

Implementing RESTful APIs using Express.js involves defining routes that


correspond to the standard HTTP methods (GET, POST, PUT, DELETE) for managing
resources. A RESTful API typically follows the principles of Representational State
Transfer (REST), where each resource is identified by a URL.

Example of a RESTful API for a simple "users" resource:

i. Setup Express Application:

const express = require('express');

const app = express();

app.use(express.json()); // Middleware to parse JSON request bodies

let users = []; // In-memory array to store user data

ii. Create (POST) a User:

app.post('/users', (req, res) => {

const user = req.body; // Get user data from request body

users.push(user); // Add user to the array

res.status(201).send(user); // Respond with the created user

});
iii. Read (GET) All Users:

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

res.send(users); // Respond with the array of users

});

iv. Read (GET) a Single User by ID:

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

const user = users.find(u => u.id === parseInt(req.params.id)); // Find user by ID

if (!user) return res.status(404).send('User not found');

res.send(user); // Respond with the found user

});

v. Update (PUT) a User:

app.put('/users/:id', (req, res) => {

const user = users.find(u => u.id === parseInt(req.params.id));

if (!user) return res.status(404).send('User not found');

Object.assign(user, req.body); // Update user data

res.send(user); /* Respond with the updated user */ });

vi. Delete (DELETE) a User:

app.delete('/users/:id', (req, res) => {

const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));

if (userIndex === -1) return res.status(404).send('User not found');

users.splice(userIndex, 1); // Remove user from the array

res.status(204).send(); /* Respond with no content*/ });

vii. Start the Server:

app.listen(3000, () => {

console.log('Server is running on port 3000');

});
Smart Training Resources India Private Limited,Chennai

Full Stack Development Part-2

Question Bank on MongoDB


2 Mark Questions & Answers:

1. Define document in MongoDB?

A document in MongoDB is a basic unit of data that is stored in a collection. It is


represented in BSON (Binary JSON) format, which allows for rich data types and
structures, including arrays and nested documents. Each document has a unique `_id`
field that serves as its primary key.

2. How do you insert a document into a MongoDB collection?

You can insert a document into a MongoDB collection using the `insertOne()` or
`insertMany()` methods.

For example:

db.collectionName.insertOne({ name: "John", age: 30 });

3. Distinguish the difference between `push( )` and `addToSet( )` in MongoDB?

The `push` operator adds a value to an array field in a document, allowing


duplicates. In contrast, the `addToSet` operator adds a value to an array only if it does
not already exist in the array, ensuring that all values in the array are unique.

4. Enlighten the different data types supported by MongoDB?

MongoDB supports various data types, including:

String: Text data.

Number: Integer or floating-point numbers.

Boolean: True or false values.

Array: An ordered list of values.

Object: A nested document.

Null: Represents a null value.

Date: Date and time values.

ObjectId: A unique identifier for documents.


5 Mark Questions & Answers:

1. Explain the concept of collections and documents in MongoDB. Provide an


example.

 In MongoDB, data is stored in documents, which are similar to JSON objects.1


 These documents are grouped into collections, which are analogous to tables in
relational databases.2
 Documents can have varying structures within the same collection.3
 Example:
 Collection: users
 Documents:

{ "_id": ObjectId("65f123456789abcdef012345"), "name": "Alice", "age": 30, "city": "New


York" }
{ "_id": ObjectId("65f987654321fedcba987654"), "name": "Bob", "age": 25, "skills":
["MongoDB", "Node.js"] }

 The _id field is automatically generated and serves as the primary key.

2. Describe the purpose and usage of the find() and findOne() methods in MongoDB.

 find() and findOne() are used to retrieve documents from a collection.


 find():
 Retrieves all documents that match a specified query.
 Returns a cursor, which allows you to iterate through the results.4
 Example: db.users.find({ age: { $gt: 25 } }) (finds users older than 25).
 findOne():
 Retrieves the first document that matches a specified query.
 Returns a single document object.
 Example: db.users.findOne({ name: "Alice" }) (finds the first user named
Alice).
 findOne() is useful when you expect only one result, while find() is used for
multiple results.

3. Explain the concept of indexes in MongoDB and their importance for query
performance.

 Indexes in MongoDB are special data structures that store a small portion of the
collection's data in an easy to traverse form.5
 They6 improve query performance by allowing MongoDB to quickly locate
documents without scanning the entire collection.
 Without indexes, MongoDB performs a collection scan, which can be slow for
large collections.7
 Indexes are created on fields that are frequently queried.
 Example: db.users.createIndex({ age: 1 }) (creates an ascending index on the age field).
 Indexes greatly speed up read operations.
4. Describe the insertMany() and insertOne() methods in MongoDB and provide an
example of their usage.

 insertOne():
 Inserts a single document into a collection.
 Example: db.products.insertOne({ name: "Laptop", price: 1200 }).
 insertMany():
 Inserts multiple documents into a collection.
 Example:
 db.products.insertMany([{ name: "Mouse", price: 20 },
{ name: "Keyboard", price: 50 },]);

 insertMany() is more efficient for inserting large amounts of data.

10 Mark Questions and Answers:

1. Explain the architecture of MongoDB and how it handles data storage.

MongoDB is a NoSQL, document-oriented database that uses a flexible schema to


store data in BSON (Binary JSON) format. Its architecture is designed for scalability,
performance, and high availability. Here are the key components of MongoDB's
architecture:

Documents: The fundamental unit of data in MongoDB is a document, which is a JSON-


like structure that can contain various data types, including arrays and nested
documents. Each document has a unique `_id` field that serves as its primary key.

Collections: Documents are grouped into collections, which are analogous to tables in
relational databases. Collections do not enforce a schema, allowing documents within
the same collection to have different structures.

Database: A MongoDB instance can contain multiple databases, each of which can have
its own collections. This allows for logical separation of data.

Storage Engine: MongoDB uses a pluggable storage engine architecture, allowing


different storage engines to be used based on the application's requirements. The
default storage engine is WiredTiger, which provides features like document-level
locking and compression.

Indexing: MongoDB supports various types of indexes (single field, compound, text,
geospatial) to improve query performance. Indexes allow for efficient data retrieval
without scanning the entire collection.

Replication: MongoDB supports replication through replica sets, which are groups of
MongoDB servers that maintain the same dataset. This ensures high availability and
data redundancy.
Sharding: To handle large datasets and high throughput, MongoDB uses sharding,
which distributes data across multiple servers. Each shard is a separate MongoDB
instance that holds a subset of the data.

Query Language: MongoDB provides a rich query language that allows for complex
queries, including filtering, sorting, and aggregation. The aggregation framework
enables advanced data processing and analysis.

Overall, MongoDB's architecture is designed to provide flexibility, scalability, and


performance, making it suitable for modern applications that require handling large
volumes of unstructured or semi-structured data.

2. Discuss the aggregation framework in MongoDB and provide an example of its


usage.

The aggregation framework in MongoDB is a powerful tool for processing and


transforming data. It allows for complex data analysis and reporting through a pipeline
of stages, where each stage performs a specific operation on the data. The aggregation
framework is particularly useful for tasks such as filtering, grouping, and calculating
statistics.

Pipeline Stages: The aggregation framework consists of multiple stages, including:

$match: Filters documents based on specified criteria.

$group: Groups documents by a specified key and performs aggregation operations


(e.g., sum, average).

$sort: Sorts the documents based on specified fields.

$project: Reshapes documents by including or excluding fields.

$limit: Limits the number of documents returned.

Example:

Suppose we have a collection named `orders` with documents that contain information
about customer orders, including fields like `customerId`, `amount`, and `status`. We
want to calculate the total sales amount for each customer whose orders are marked as
"completed."

Here’s how you can use the aggregation framework to achieve this:

db.orders.aggregate([

$match: { status: "completed" } // Filter for completed orders


},

$group: {

_id: "$customerId", // Group by customerId

totalSales: { $sum: "$amount" } // Calculate total sales for each customer

},

$sort: { totalSales: -1 } // Sort by total sales in descending order

]);
Smart Training Resources India Private Limited,Chennai

Full Stack Development Part-2

Question Bank on NodeJs


2 Mark Questions & Answers:

1. Explain the purpose of the `package.json` file in a Node.js project?

The `package.json` file is a manifest file that contains metadata about the project,
including its name, version, dependencies, scripts, and other configurations. It is
essential for managing project dependencies and scripts.

2. How do you install a package using npm?

**Answer:** You can install a package using npm (Node Package Manager) by running
the command `npm install <package-name>` in the terminal. This command downloads
the package and adds it to the `node_modules` directory.

3. Illustrate the difference between `require` and `import` in Node.js?

`require` is a CommonJS module system used in Node.js to include modules,


while `import` is part of the ES6 module system. `require` is synchronous and can be
used in any part of the code, whereas `import` is asynchronous and must be used at the
top level of the module.

4. How do you create a simple HTTP server in Node.js?You can create a simple
HTTP server in Node.js using the `http` module as follows:

const http = require('http');

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

res.statusCode = 200;

res.setHeader('Content-Type', 'text/plain');

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

});

server.listen(3000, () => {

console.log('Server running at http://localhost:3000/');

});
5 Mark Questions & Answers:

1. Describe Promises in Node.js, and how do they improve asynchronous


programming?

Promises are a modern way to handle asynchronous operations in JavaScript,


including Node.js. They represent a value that may be available now, or in the future, or
never. Promises improve asynchronous programming in several ways:

State Management: A Promise can be in one of three states: pending, fulfilled, or


rejected. This state management allows developers to handle success and failure
scenarios more effectively.

Chaining: Promises can be chained using `.then()` and `.catch()` methods, allowing for
cleaner and more readable code. This eliminates the "callback hell" problem, where
nested callbacks make code difficult to read and maintain.

Error Handling: Promises provide a centralized way to handle errors. If a promise is


rejected, the error can be caught in a single `.catch()` block, making it easier to manage
error scenarios.

```javascript

const fs = require('fs').promises;

fs.readFile('file.txt', 'utf8')

.then(data => {

console.log(data);

})

.catch(err => {

console.error('Error reading file:', err);

});

Alright, let's tackle some 5-mark questions on Node.js, focusing on concepts that
require more detailed explanations:

2. Explain the Node.js event loop and how it handles asynchronous operations.

 Node.js is single-threaded, but it achieves high concurrency through its event


loop.
 The event loop constantly monitors the call stack and the callback queue.
 When an asynchronous operation (e.g., file I/O, network requests) is initiated,
it's offloaded to the operating system.
 Once the operation completes, the operating system places the callback function
into the callback queue.
 The event loop checks if the call stack is empty. If it is, it takes the first callback
from the queue and pushes it onto the call stack4 for execution.
 This process repeats continuously, allowing Node.js to handle multiple
asynchronous operations without blocking the main thread.
 This non-blocking I/O model is what makes Node.js efficient for handling
concurrent requests.

3. Describe the usage of the fs module for file system operations in Node.js,
providing examples of reading and writing files.

 The fs (file system) module provides functions for interacting with the file
system, enabling Node.js to perform tasks like reading, writing, and deleting files.
 Reading a file example:

JavaScript

const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {


if (err) {
console.error(err);
return;
}
console.log(data);
});

 Writing10 to a file example:

JavaScript

const fs = require('fs');

const content = 'This is some text to write to the file.';

fs.writeFile('output.txt', content, (err) => {


if (err) {
console.error(err);
} else {
console.log('File written successfully.');
}
});

 The fs module provides both synchronous and asynchronous functions.


Asynchronous functions are generally preferred for better performance.
4. Explain the concept of modules in Node.js and how module.exports and
require() are used.

 Modules are reusable blocks of code that can be imported and used in other
parts of a Node.js application.
 Node.js uses the CommonJS module system.
 module.exports is used to expose functions, objects, or variables from a module,
making them available for use in other files.
 require() is used to import modules into a file. It takes the module's file path as
an argument and returns the exported object.
 Example:

JavaScript

// module.js
const myFunction = () => {
return 'Hello from the module!';
};

module.exports = myFunction;

// app.js
const myModuleFunction = require('./module.js');

console.log(myModuleFunction()); // Output: Hello from the module!

 Modules promote code organization, reusability, and maintainability.

10 Mark Questions and Answers:

1. Explain the architecture of Node.js and how it handles asynchronous


operations.

Node.js is built on a non-blocking, event-driven architecture that allows it to


handle multiple connections simultaneously. Its architecture can be broken down into
several key components:

Single-threaded Event Loop: Node.js operates on a single-threaded event loop, which


means it uses a single thread to handle all incoming requests. This design allows Node.js
to manage multiple connections without the overhead of creating multiple threads,
making it lightweight and efficient.

Asynchronous I/O: Node.js uses non-blocking I/O operations, which means that when
a request is made (e.g., reading a file or querying a database), Node.js does not wait for
the operation to complete. Instead, it registers a callback function and continues
executing other code. Once the I/O operation is complete, the event loop picks up the
callback and executes it.
Event-Driven Model: The event-driven model allows Node.js to respond to events (like
incoming requests) and execute the corresponding callback functions. This model is
facilitated by the `EventEmitter` class, which allows objects to emit events and register
listeners.

Callback Functions and Promises: Node.js heavily relies on callback functions for
handling asynchronous operations. However, to improve code readability and
manageability, Promises and async/await syntax have been introduced, allowing
developers to write asynchronous code in a more synchronous manner.

Example:

const fs = require('fs');

console.log('Start reading file...');

fs.readFile('example.txt', 'utf8', (err, data) => {

if (err) throw err;

console.log('File content:', data);

});

console.log('File read initiated...');

2. Discuss the role of the `npm` package manager in Node.js and how to create a
package.

`npm` (Node Package Manager) is the default package manager for Node.js, and it
plays a crucial role in managing libraries and dependencies in Node.js applications. Here
are the key aspects of `npm`:

Package Management: `npm` allows developers to easily install, update, and manage
third-party libraries and packages. It provides a vast repository of open-source
packages that can be integrated into applications.

Dependency Management: When a package is installed, `npm` automatically resolves


and installs its dependencies, ensuring that all required libraries are available for the
application to function correctly.

Scripts and Automation: `npm` allows developers to define scripts in the


`package.json` file, enabling automation of common tasks such as testing, building, and
starting the application.

Creating a Package:

i.Initialize a New Project: To create a new package, navigate to your project directory
and run:
npm init

This command prompts you to enter details about your package, such as name,
version, description, entry point, and more. It generates a `package.json` file.

ii. Add Dependencies: You can add dependencies using

npm install <package-name>

This command installs the specified package and updates the `package.json` file with
the new dependency.

iii. Publishing a Package: To publish your package to the npm registry, you need to
create an account on the npm website. After logging in via the command line using `npm
login`, you can publish your package with:

npm publish

Example of `package.json`:

"name": "my-awesome-package",

"version": "1.0.0",

"description": "A simple example package",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"dependencies": {

"express": "^4.17.1"

You might also like