Smart Training Resources India Private Limited, Chennai Fullstack Development Part-I Question Bank Questions in CSS
Smart Training Resources India Private Limited, Chennai Fullstack Development Part-I Question Bank Questions in CSS
Question Bank
Questions in CSS:
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;
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;
}
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:
.nav {
display: flex;
justify-content: space-around;
}
.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
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.
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:
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>
<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.
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.
<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
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:
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.
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.
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);
};
}
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:
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.
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.
2. filter(): Creates a new array with all elements that pass the test implemented by the
provided function.
3. reduce(): Applies a function against an accumulator and each element in the array to reduce
it to a single value.
8. Explain the concept of asynchronous programming in JavaScript. How does the async/await syntax
simplify working with promises? Provide an example.
Basic Syntax:
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
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.
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.
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.
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.
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.
Ans. State in React represents dynamic data that influences what gets rendered. Local component state
can be managed using:
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.
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.
To install:
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.
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';
@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>
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.
we will create a simple Angular application that uses ngSwitch to display different
messages based on the selected option from a dropdown menu.
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
@Component({
selector: 'app-switch-example',
templateUrl: './switch-example.component.html',
styleUrls: ['./switch-example.component.css']
})
export class SwitchExampleComponent {
selectedOption: string = 'option1'; // Default option
<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>
typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // Import FormsModule
@NgModule({
declarations: [
AppComponent,
SwitchExampleComponent
],
imports: [
BrowserModule,
FormsModule // Add FormsModule here
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<app-switch-example></app-switch-example>
npm start
‘’’’’’’
2. Create and Design an Counter App to Increase, Decrease and Reset a Value
using data and event binding in Angular.
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
@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css']
})
export class CounterComponent {
count: number = 0; // Initialize the counter value
<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>
.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;
}
<app-counter></app-counter>
npm start
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.
res.status(500).send('Something broke!');});
i. Logging Middleware:
console.log(`${req.method} ${req.url}`);
});
console.error(err.stack);
res.status(500).send('Something broke!');
});
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:
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.
try {
// Simulate an error
} catch (err) {
});
// Error-handling middleware
});
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.
1. First, create a directory named `public` and place your static files (e.g., `index.html`,
`style.css`) inside it.
app.use(express.static('public'));
app.listen(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.
});
iii. Read (GET) All Users:
});
});
app.listen(3000, () => {
});
Smart Training Resources India Private Limited,Chennai
You can insert a document into a MongoDB collection using the `insertOne()` or
`insertMany()` methods.
For example:
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.
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 },]);
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.
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.
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([
$group: {
},
]);
Smart Training Resources India Private Limited,Chennai
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.
**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.
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:
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(3000, () => {
});
5 Mark Questions & Answers:
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.
```javascript
const fs = require('fs').promises;
fs.readFile('file.txt', 'utf8')
.then(data => {
console.log(data);
})
.catch(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.
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');
JavaScript
const fs = require('fs');
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');
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');
});
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.
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.
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",
"main": "index.js",
"scripts": {
},
"dependencies": {
"express": "^4.17.1"