WC-Naufil Sir
[Link] how the Event Loop works with a mix of setTimeout, Promise, and
synchronous code.
ANS-> The Event Loop is the heart of [Link] is the central mechanism that handles
all asynchronous operations in a single-threaded environment. Although JavaScript
executes on one thread, [Link] achieves concurrency using the Event Loop and libuv,
which manages background threads for I/O tasks.
The Event Loop continuously checks the Call Stack and Task Queues and executes
code in a specific order. It ensures that synchronous and asynchronous tasks don’t
block each other.
Execution Flow:
1. Synchronous code runs first — placed directly on the call stack.
2. Once synchronous code finishes, Microtasks (like Promises or
[Link]()) are executed.
3. Then, Macrotasks such as setTimeout() or I/O callbacks are processed.
Example:
[Link]("Start");
setTimeout(() => [Link]("setTimeout executed"), 0);
[Link]().then(() => [Link]("Promise resolved"));
[Link]("End");
Output:
Start
End
Promise resolved
setTimeout executed
Explanation:
• The synchronous code (Start, End) executes first.
• The Promise callback, being a microtask, executes next.
• Finally, setTimeout executes as a macrotask after the current event loop
iteration.
Phases of the Event Loop:
1. Timers Phase → Executes setTimeout() and setInterval().
2. Pending Callbacks → Handles I/O callbacks.
3. Poll Phase → Waits for new I/O events.
4. Check Phase → Executes setImmediate() callbacks.
5. Close Callbacks → Closes resources like sockets.
Conclusion:
The Event Loop allows [Link] to perform non-blocking asynchronous operations
efficiently, even on a single thread. It ensures that Promises and setTimeouts are
executed in a predictable sequence, maintaining high concurrency and smooth
performance.
2. Differentiate between Buffers and Streams.
Aspect Buffers Streams
Temporary memory storage for Continuous flow of data chunks for
Definition
raw binary data. reading or writing.
Data Loads entire data into memory Processes data piece by piece (chunk
Handling before processing. by chunk).
Memory High memory usage for large Low memory usage; handles large files
Usage files. efficiently.
Nature Static and finite in size. Dynamic and continuous.
Image processing, file chunks, Reading/writing large files, video
Use Case
binary operations. streaming, network sockets.
Buffers are the building blocks Streams rely on Buffers to transport
Relation
used by Streams. data.
Example:
• Buffer: [Link]('Hello') creates a binary data block.
• Stream: [Link]('[Link]') reads file data in chunks.
Conclusion:
Buffers deal with complete data, while Streams manage ongoing data flow, making
them ideal for performance-critical I/O operations.
[Link] is the difference between [Link]() and [Link]()?
The fs (File System) module in [Link] enables reading, writing, and manipulating
files.
The main difference between [Link]() and [Link]() lies in how they
handle the Event Loop and I/O operations.
1. [Link]() – Asynchronous
• Uses a non-blocking approach.
• Delegates the task to libuv’s thread pool, allowing the Event Loop to continue.
• The result is returned through a callback or Promise once the file is read.
Example:
const fs = require('fs');
[Link]('[Link]', 'utf8', (err, data) => {
if (err) throw err;
[Link](data);
});
[Link]("Reading file asynchronously...");
Output:
Reading file asynchronously...
<File contents>
2. [Link]() – Synchronous
• Uses a blocking approach.
• The Event Loop stops until the file is completely read.
• Suitable only for scripts that don’t require concurrency.
Example:
const fs = require('fs');
const data = [Link]('[Link]', 'utf8');
[Link](data);
[Link]("File read complete");
Output:
<File contents>
File read complete
Comparison Table:
Aspect [Link]() [Link]()
Type Asynchronous (Non-blocking) Synchronous (Blocking)
Execution Continues without waiting Halts until task completes
Performance High for concurrent requests Low for multi-client apps
Return Type Uses callback or Promise Returns data directly
Usage Servers, web apps Startup scripts, configuration
Conclusion:
[Link]() should be used for real-time, scalable applications, while
[Link]() is best for simple scripts or initial setup operations where blocking
is acceptable.
4. What happens when multiple clients connect to the same server?
When multiple clients connect to a [Link] server (e.g., HTTP or TCP server),
[Link] handles all connections using its event-driven, non-blocking
architecture.
Unlike traditional multi-threaded servers, [Link] uses a single thread to
manage thousands of connections simultaneously.
Working:
1. Each new client connection triggers an event (like 'connection' or 'request').
2. The Event Loop listens for incoming events and delegates heavy operations to
libuv’s thread pool.
3. The main thread continues to serve other clients while waiting for I/O
completion.
4. Once an I/O task completes, its callback is placed back in the Event Queue to be
executed by the Event Loop.
Example:
const http = require('http');
const server = [Link]((req, res) => {
[Link](200, {'Content-Type': 'text/plain'});
[Link]('Hello, Client!');
});
[Link](3000, () => [Link]('Server running on port 3000'));
Here, even if hundreds of clients connect simultaneously, each request is
handled efficiently without blocking others.
Key Points:
• [Link] doesn’t create a new thread for each client.
• It maintains scalability using non-blocking I/O and callbacks.
• Heavy tasks like file reading or database queries are offloaded to background
threads.
Advantages:
• High scalability – thousands of concurrent users.
• Efficient resource use – minimal CPU and memory overhead.
• Low latency – Event Loop ensures quick request-response cycles.
Conclusion:
When multiple clients connect, [Link] efficiently handles all connections using
the event-driven model and libuv thread pool. This makes it perfect for real-time,
data-intensive applications like chats, live updates, and streaming platforms.
SNS
Q1. Create a simple React application that fetches data from an external API and
displays it in a list format. Describe the steps involved.
ANS: Fetching data from an external API is a common task in React applications.
It is used to show live or changing information on the website. In React, we can
handle this using hooks like useState and useEffect. The process includes
setting up the project, fetching the data, storing it in a state, and then displaying
it in the UI.
Step 1: Project Setup
Before creating the component, we must set up a React project.
• Requirements: Make sure [Link] and npm are installed on your system.
• Creating the Project: Open the terminal and type the following command:
• npx create-react-app my-api-app
This command will create a new React project with all necessary files and folders.
Step 2: Fetching Data and Managing State
We will use a functional component and React hooks to fetch data and manage
state.
• useState Hook: Used to create a state variable that stores the data received from
the API.
• useEffect Hook: Used to run side effects such as fetching data from an API when
the component first loads.
Example Code:
import React, { useState, useEffect } from 'react';
function DataDisplay() {
const [items, setItems] = useState([]); // state to store data
// useEffect runs only once when the component loads
useEffect(() => {
fetch('[Link] //api to fetch data
.then(res => [Link]()) // convert response to JSON
.then(data => setItems(data)); // store data in items
}, []);
return (
<div>
<h1>API Data</h1>
<ul>
{[Link](item => (
<li key={[Link]}>{[Link]}</li>
))}
</ul>
</div>
);
}
export default DataDisplay;
Step 3: Displaying the Data
After fetching the data, we display it in the browser.
• Conditional Rendering: A loading message can be shown until the data is fetched
completely.
• Using map(): Once the data is available, the map() function is used to loop
through the array and display each item.
• Key Attribute: Each list item should have a unique key (for example, [Link]) so
React can manage the list efficiently.
Conclusion:
The steps to fetch and display data in React are:
1. Create a React app using create-react-app.
2. Use useState to store the fetched data.
3. Use useEffect to fetch the data when the component loads.
4. Use fetch() to call the external API.
5. Display the data in a list using map().
This process helps React applications show real-time data from external sources
in an efficient and simple way.
Q6. Describe how REST APIs function in web development and provide an
example of an HTTP GET request.
Answer:
REST (Representational State Transfer) APIs are a set of rules used to build and
interact with web services.
They act as a way for a client (like a web browser or mobile app) and a server to
communicate and exchange data over the HTTP protocol in a standard way.
How REST APIs Function
REST APIs follow some main principles that make them easy to use, flexible, and
scalable in web development.
1. Client–Server Architecture:
The client (frontend) handles what users see and interact with, while the server
(backend) stores and manages the data.
Both can work and be updated separately without affecting each other.
2. Statelessness:
Every request sent from the client to the server must include all the information
needed for the server to process it.
The server does not remember previous requests — each one is independent.
3. Resources:
In REST, everything that can be shared or accessed is called a resource.
Examples include a user, a product, or a post.
Each resource has a unique URL (endpoint) like /api/users/123.
4. HTTP Methods:
REST APIs use standard HTTP methods to perform actions on resources:
o GET: Retrieve data or a resource.
o POST: Create a new resource.
o PUT / PATCH: Update an existing resource.
o DELETE: Remove a resource.
5. Data Format:
When a client requests data, the server sends a representation of that data.
The most common format used is JSON (JavaScript Object Notation) because
it’s light, easy to read, and works well with JavaScript.
Example of an HTTP GET Request
A GET request is used to retrieve data from the server.
Example:
If you want to get a list of products from an online store’s API, you would send a
GET request to the products endpoint.
• Method: GET
• URL / Endpoint:
• [Link]
Response:
If the request is successful, the server sends back a 200 OK status code along
with the requested data in JSON format.
Sample JSON Response Body:
[
{ "id": 1, "name": "Laptop", "price": 50000 },
{ "id": 2, "name": "Mobile", "price": 20000 }
]
2. Explain the concept of state and props in React. How do they differ, and how are
they used in components
Props, short for "Properties," are used to pass data from a parent component
to a child component, establishing a one-way (unidirectional) data flow. They
work just like function arguments, allowing components to be configured
and customized from the outside.
A crucial feature of props is that they are read-only. A component can never
modify the props it receives; they are immutable.
How Props are Used:
Props are passed as attributes in JSX and accessed differently in functional and
class components.
In Functional Components, props are received as the single argument to the
function.
## What is State?
The state is a built-in React object that holds data or information that is private
and managed within a component. Unlike props, a component's state is mutable
and can change over time, typically in response to user actions (like button
clicks) or system events.
The most important feature of state is that whenever it changes, the component
automatically re-renders to reflect the updated information on the screen.
How State is Used:
The method for managing state depends on the component type.
In Class Components, state is initialized in the constructor and can only be
modified using the [Link]() method. Directly changing [Link] will not
trigger a re-render.