FSD Notes
FSD Notes
Q1. Describe the evolution from Web 1.0 to Web 3.0. Highlight at least three key differences
between each generation.
Web 1.0 is the first generation of the web. It is also known as the Static Web. In this stage, websites
were simple and had very basic content. The main purpose was to show information to users, just
like newspaper or a digital book.
Web 2.0 brought a big change. It allowed users to interact with websites and also share their own
content. This is the web we use the most today. It’s known as Dynamic Web or the Social Web.
This generation gave rise to many Full Stack Developers, as websites now needed both fronted and
backend work
Web 3.0 is the latest stage, still being developed. If focuses on making the wen smarter, more
private, and more personalized. It uses technologies like AI, Machine Learning, Blockchain, and
Semantic Web.
Key Differences
1. Content Type
In Web 1.0, users could only read the content. There were no options to comment, like, or post
anything. Websites were just digital pages full of information.
This version allowed users to both read and write content. You could post pictures, write blogs,
comment on posts, and share your thoughts.
🤖 Web 3.0 – Read, Write, and Own
Now users can also own the content they create. This means no company can remove your data. You
control your own photos, posts, and even digital money using blockchain.
2. User Role
Users were only readers. They could not change anything. There was no login or profile creation.
Now, users can register, log in, and become content creators. YouTube videos, Instagram posts, and
blogs are created by normal users.
Users become owners of their content and identity. You can create your own digital wallet and
control how your data is used online.
3. Technology Used
Websites were built using only HTML and basic CSS. There was no JavaScript, so everything was
simple and not interactive.
Web 2.0 uses more powerful coding tools like JavaScript for interactivity, PHP for server-side logic,
and AJAX for faster updates without reloading the page.
Web 3.0 uses smart technologies like Artificial Intelligence (AI), Blockchain for security and privacy,
and Machine Learning (ML) for recommendations and personalization.
4. Control
In Web 1.0, all data and control were with the website owners or developers. Users had no control.
Even in Web 2.0, companies like Facebook and Google control your data and can remove or track
your activity.
Web 3.0 changes this. Data is stored in a distributed way, not controlled by a single company. You
have more freedom and privacy.
5. Example Sites
🌐 Web 1.0
🔄 Web 2.0
🤖 Web 3.0
Ethereum (Blockchain platform), IPFS (decentralized file system), Brave Browser (privacy-
based), DApps (Decentralized Apps)
6. Interaction Level
You can interact in many ways – comment, share, like, follow, and even message others.
Interaction is more personal and secure. AI helps websites understand your needs and show you
smart suggestions.
7. Data Ownership
Only the website creator or company had the data. Users didn’t even have accounts.
Big companies like Google, Facebook, and Amazon store your data. They can use it to show ads or
sell to third parties.
Now users own their data. They use digital wallets and can decide who accesses their data. No
company can use it without permission.
Conclusion
Q2. Explain the architecture and components of a typical Web Service. Use a labelled diagram to
support your answer.
What is a Web Service?
A Web Service is a way of communication between two devices over the web. It helps one
application to interact with another using standard web protocols like HTTP. In simple words, a web
service allows data to be sent and received between software systems, even if they are built using
different programming languages or platforms.
For example, an Android app can use a web service written in Java or PHP to fetch user data from a
database.
1. Service Provider
3. Service Registry
3. Bind – The client connects with the service provider and uses the service.
1. Service Provider
This is the system that creates and hosts the wen service
It writes the code that provides some functionality – for example, checking login or saving a
message
The provider publishes the service description (WSDL) to the registry
Example: A bank server provides a service to check a account balance.
3. Service Registry
Technology Involved
Technology Purpose
REST A simpler, lighter protocol using HTTP methods (GET, POST, etc.)
WSDL An XML file that describes the web service and its functions
Language Independent – Java, Python, .NET, etc., can all talk to each other.
Platform Independent – Works on Windows, Linux, mobile, etc.
Conclusion
Q3. Create a basic Web API using ASP.NET Core that returns a list of books with title and
author. Describe the HTTP methods used.
A Web API allows communication between different software applications over the web. It
provides data that clients (like web browsers, or mobile apps) can request.
Steps
Step1: Setup a New ASP.NET Core Web API Project
1. GET Method
In this example, [HttpGet] is used in the GetBooks() method to return the list of books.
This method does not change any data; it only reads information.
Q4. Compare Browser APIs and Third-party APIs in terms of accessibility, security, and
scope. Provide one example of each.
API stands for Application Programming Interfaces. APIs allow different program to talk to
each other and share data. Mainly we usually work with two main types of APIs:
1. Browser APIs
2. Third-Party APIs
✅ Key Points:
Third-party APIs are developed and maintained by companies or organizations other than the
browser maker. These APIs are hosted on external servers and allow you to connect your web app
with services like Google Maps, Twitter, OpenWeather, etc.
✅ Key Points:
Accessibility Built into browsers, always available Need internet and API keys to access
Security Secure, runs in sandbox mode Needs secure handling of keys and tokens
Explanation of Differences
🔸 Accessibility
Browser APIs are always accessible when a user opens a browser. No setup is needed. For
example, the Geolocation API can be used just by calling a JavaScript function.
Third-party APIs require a network connection. You may need to sign up and get an API key
to use them. Example: Google Maps API needs an API key and billing account.
🔸 Security
Browser APIs are secure because they run inside the browser's "sandbox". They cannot harm
the system.
Third-party APIs can be risky if API keys are exposed. Developers must use HTTPS and hide
sensitive data on the server-side.
🔸 Scope
Browser APIs help with features already in the browser — like detecting location, working
with the clipboard, or storing small data.
Third-party APIs are more powerful and cover services outside the browser, like accessing a
database, making payments, or integrating with social media.
Q5. Evaluate the role of security in Web Services. Discuss at least three standards or
practices used to ensure secure communication.
Web services allow different software applications to talk to each other over the internet.
For example, a mobile app may use a web service to check the weather, make payments, or
store user data in the cloud.
But when applications talk over the internet, they can face security risks like:
Hackers stealing data
Fake users accessing the service
Tampering with data during transfer
So, security in web services is very important. Without it, personal information, financial
data, or even the system itself can be harmed.
✅ What is HTTPS?
It encrypts the data sent between the browser and the server using SSL (Secure Socket
Layer) or TLS (Transport Layer Security).
✅ How it helps:
Prevents data sniffing: Hackers can't read the data even if they capture it.
Verifies the website: A valid certificate proves that the website is trusted.
✅ Example:
When you open https://www.bank.com, your data is encrypted while being sent to the server. No
one can see your account details or password in between.
All RESTful or SOAP web services should use HTTPS instead of plain HTTP to keep data secure.
2. Authentication and Authorization (OAuth, JWT)
✅ What is Authentication?
✅ What is Authorization?
Example: Some users can only view data; others can edit or delete.
✅ Common Techniques:
Allows one website to access your information on another site without sharing passwords.
✅ Why Important?
Stops SQL Injection: A hacker may enter code in input fields to access the database.
Stops Cross-site Scripting (XSS): Inserting scripts that run in users' browsers.
✅ Best Practices:
Q6. Design a web application workflow that consumes a third-party API (e.g., weather,
news, or currency converter) and displays results on a webpage. Explain the steps
involved.
HTML Code
JS Code
1. Pick an API
Choose an API that gives you the data you need, like weather or news.
2. Sign Up and Get API Key
Register on the API website and get your own API key. This key helps the API know who is
using it.
9. Handle Errors
If something goes wrong (like wrong city name), show a message to the user.
5 Marks (Module 5)
Q1. Define Web 1.0, Web 2.0, and Web 3.0. Provide one key characteristic of each.
Web 1.0 is the oldest version of the internet, which was mostly used in the 1990s to early 2000s. In
this stage, websites were very simple. They had text, images, and links, but you could only read the
information. You could not interact with the website much.
It was called the "read-only web" because users could only read what was written on websites.
Static Pages – Web 1.0 had web pages that did not change unless the website owner updated them
manually.
It gave rise to many popular websites like Facebook, YouTube, Wikipedia, and Instagram.
User-Generated Content – In Web 2.0, users can create and share their own content like photos,
videos, and posts.
Web 3.0 is the latest stage of the internet, and it is still growing. It uses new technologies like
Artificial Intelligence (AI), Blockchain, and Machine Learning. It’s also called the "read-write-own
web" because now users can own their data and control how it is used.
Decentralization – Web 3.0 uses blockchain, where no single company controls all the data. Users
have more power over their own information.
Conclusion
The web has changed a lot from Web 1.0 to Web 3.0.
Web 3.0 is smarter and gives users more control and privacy.
Q2. Explain the main differences between Browser APIs and Third-Party APIs. Provide one
example of each.
1. What are Browser APIs?
Browser APIs are built-in tools provided by web browsers like Chrome, Firefox, or Safari.
These APIs allow web developers to use special features of the browser directly in their
websites or web applications.
They help interact with the browser’s environment, hardware, or built-in functions.
Browser APIs are always available inside the browser without needing to install anything
extra.
They are mainly used for tasks like working with the web page’s content, handling
multimedia, controlling browser history, and accessing device features.
Geolocation API:
This API lets websites find the user’s location using GPS or IP address (with the user’s
permission). For example, a weather website can show weather information based on your
current location using the Geolocation API.
Third-Party APIs are created and provided by companies or organizations that are not part of
the browser.
These APIs let developers connect their applications with external services or platforms.
Using third-party APIs, developers can add extra features to their apps without building them
from scratch.
These APIs usually require registration or an API key to use, and developers send requests
over the internet to get data or perform actions.
Third-party APIs are often used to access services like payment gateways, social media,
maps, messaging, or cloud storage.
Difference
Who provides it Web browsers (like Chrome, Firefox) External companies or service providers
Where it runs Inside the web browser On external servers, accessed via internet
Purpose Access browser features and device Access external services and data
Q3. What are the key characteristics of Web Services? List and briefly explain any three.
Web Services are software systems designed to support communication between different
applications over the internet. They allow applications to talk to each other, regardless of the
platforms or languages they are built on.
1. Interoperability
2. Loose Coupling
3. Standardized Protocols
4. Reusability
5. Discoverability
6. Statelessness
1. Interoperability
Meaning:
Interoperability means that web services can work and communicate with different software
applications regardless of the programming language, platform, or device they use.
Example:
A web service created in Java can be used by an application written in Python or .NET
without any problems.
Importance:
This allows different systems to exchange data smoothly, making integration easier between
various technologies.
2. Loose Coupling
Meaning:
Loose coupling means that the web service and the client using it are independent of each
other. Changes made to the web service will have minimal or no effect on the client and vice
versa.
Example:
If the web service changes its internal logic or database, the client application does not need
to be changed as long as the service interface remains the same.
Importance:
This makes web services flexible and easier to maintain or upgrade without breaking the
client applications.
3. Standardized Protocols
Meaning:
Web services use standard internet protocols like HTTP, SOAP, REST, and XML/JSON for
communication.
Example:
A web service might use RESTful API calls over HTTP to send and receive data in JSON format.
Importance:
Using standard protocols ensures that web services can work over the internet easily and
communicate with other web-based systems reliably.
Q4. Demonstrate how to call a third-party API (e.g., OpenWeather API) in a browser using
JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>OpenWeather API Example</title>
</head>
<body>
<h2>Check Weather</h2>
<button onclick="getWeather()">Get Weather</button>
<p id="weatherResult"></p>
<script>
function getWeather() {
// Replace YOUR_API_KEY with your actual OpenWeather API key
const apiKey = 'bb2b12632395f4a2abd885bac37b63b6';
const city = 'London';
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=$
{apiKey}&units=metric`;
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// Extract temperature and description from response
const temp = data.main.temp;
const description = data.weather[0].description;
</body>
</html>
Q5. Create a web api to find sum of two numbers using asp.net
1. Create a new ASP.NET Core Web API Project
You can use Visual Studio or the command line:
2. Create a Controller
In the Controllers folder, add a new controller named SumController.cs.
Q6. Compare and contrast SOAP and REST web services based on architecture, data
format, and usage.
SOAP follows a strict protocol with a REST is an architectural style that uses
defined standard based on XML standard HTTP methods (GET, POST,
messaging. It uses a contract called PUT, DELETE). It is simpler and focuses
Architecture WSDL (Web Services Description on resources identified by URLs
Language) to describe the service. It (Uniform Resource Locators). It is
relies heavily on standards like WS- stateless and doesn’t require a
Security, WS-Addressing, etc. contract like WSDL.
Q8. Analyse the role of XML in Web Services and explain how WSDL uses XML to describe
service interfaces.
Role of XML in Web Services
XML (eXtensible Markup Language) is a flexible, text-based format used to structure
data in a way that is both human-readable and machine-readable.
In Web Services, XML plays a crucial role because it allows data to be exchanged
between different systems regardless of their platform, programming language, or
hardware.
Web services use XML to format messages so that different applications can
understand and process them without conflicts.
For example, SOAP (Simple Object Access Protocol), a common protocol for web
services, relies entirely on XML to package requests and responses.
XML’s self-describing nature means the data includes tags that explain what each
piece of information is, making it easy to parse and validate.
How WSDL Uses XML to Describe Service Interfaces
WSDL (Web Services Description Language) is an XML-based language used
specifically to describe the details of a web service.
It defines what the service does, how to access it, and what data it expects and
returns.
The WSDL document itself is written in XML and includes several important parts:
o Types: Describes the data types (like integers, strings, complex objects) used
by the service using XML Schema.
o Messages: Defines the input and output messages (the data being sent and
received).
o PortType: Specifies the operations (functions or methods) the service offers
and the messages involved.
o Binding: Describes how the service can be accessed (e.g., using SOAP over
HTTP).
o Service: Specifies the service endpoint, i.e., the URL where the service is
available.
Because WSDL is XML, machines can automatically read it, understand what the
service does, and generate the code necessary to communicate with it.
This helps developers use the web service without manually understanding its
implementation, improving interoperability.
Q9. Evaluate the importance of security in Web Services. Describe any two common
security standards used.
Importance of Security in Web Services
Web Services allow different applications to communicate over the internet by exchanging
data and performing operations remotely. Because they often handle sensitive information
like personal data, financial transactions, or business-critical operations, security is very
important in Web Services for the following reasons:
1. Protecting Data Privacy
Web services may send and receive confidential data. Without proper security, this
data can be intercepted by attackers, leading to privacy breaches.
2. Ensuring Data Integrity
Data sent between clients and services must not be tampered with or altered during
transmission. Security ensures that the data received is exactly what was sent.
3. Authentication and Authorization
It is important to verify that the users or applications requesting access to the web
service are who they claim to be (authentication). Also, they should only be allowed
to perform actions they are permitted to (authorization).
4. Preventing Attacks
Without security, web services are vulnerable to attacks like man-in-the-middle,
replay attacks, or denial of service (DoS), which can disrupt operations or steal
information.
5. Building Trust
Secure web services build trust between businesses and users because users feel
safe sharing their data and relying on the service.
Q2. Write a Ruby program that uses different types of loops (while, until, for, each) to
print numbers from 1 to 10. Explain the output.
Code
Output
🧠 Explanation
1. while loop
2. until loop
Starts from j = 1, and runs until j > 10, which means from 1 to 10.
3. for loop
Loops through a range (1..10).
4. each loop
Q3. Describe the structure of a Ruby on Rails application. Explain the role of Models,
Views, and Controllers (MVC).
Ruby on Rails also called Rails is a powerful web application framework written in Ruby. Rails
follow the MVC (Model View Controller) architecture, which helps organize code clearly and
makes development easier and faster.
Basic Structure
1. app/
This is the heart of your application and contains:
models/ – Your data and logic (database-related).
views/ – HTML templates for what the user sees.
controllers/ – Logic to connect models and views.
2. config/
This folder contains configuration files, including routes.rb, which maps URLs to controller
actions.
3. db/
Stores your database and migration files.
4. public/
Holds static files like HTML, images, and CSS.
5. Gemfile
Lists the Ruby libraries (gems) your app uses.
1️Model
What it does: Manages data and business logic.
Where it lives: app/models
Role: Connects with the database to store and retrieve data.
Example: If you have a blog app, the Post model will handle all the logic related to
posts (like title, content, author).
Controller
Role: Receives user input, communicates with the model, and selects the correct view.
2. The controller calls the Model (Post.all) to get data from the database.
Benefits
Separation of concerns – Keeps logic, data, and user interface separate for better clarity.
Easy to manage – Each part of the app is placed in its own folder, making files easy to find and
update.
Reusable code – Models and views can be reused in different parts of the app without rewriting
code.
Clean architecture – The structure is organized and scalable, making the app easier to grow and
maintain.
Q4. Demonstrate how to define a module in Ruby. Then, show how the module can be
included in a class and used.
What is a Module in Ruby?
A module in Ruby is a collection of methods, constants, and variables. It is used to organize
code and share behaviour across multiple classes.
Modules cannot be instantiated like classes.
Modules are used with include or extend in a class
Step-by-Step: Defining and Using a Module
1. Define a Module
We use include Greetings to add the module's methods to the Person class.
3. Create Object and Use Module Methods
Output
After that, the class can use the methods of the module just like its own methods.
Q5. Explain how ActiveRecord works in Ruby on Rails. Include a discussion of migrations
and associations.
What is ActiveRecord in Ruby on Rails?
ActiveRecord is the ORM (Object-Relational Mapping) tool used in Ruby on Rails. It acts like
a bridge between your Ruby code and the database. With ActiveRecord, you can create,
read, update, and delete data from the database using simple Ruby commands — no need
to write raw SQL.
Key Features of ActiveRecord
3. Handles all database operations like insert, update, delete, and select using Ruby methods.
Migrations are a way to create and change database tables using Ruby code. Instead of writing SQL
commands like CREATE TABLE, we write migrations in Ruby.
This creates a students table with name, age, and timestamp fields.
You can run this using rails db:migrate.
Benefits of Migrations
Associations define relationships between models (tables). These relationships reflect how the data
is connected in the real world.
💬 Types of Associations
1. belongs_to
2. has_one
3. has_many
4. has_many :through
5. has_and_belongs_to_many
1. One-to-Many Relationship
2. One-to-One Relationship
Example: A Doctor can have many Patients, and a Patient can visit many Doctors
Q6. Describe how Ruby handles Strings and Arrays. Provide examples of at least three
string methods and three array methods.
What is a String in Ruby?
In Ruby, a string is a sequence of characters. You can store text like words, sentences, or
even symbols inside strings. Strings in Ruby are mutable, which means you can change their
content.
Output
Explanation: This method changes all small letters into capital letters.
2. length – Find the number of characters
Output
Explanation: It counts and returns how many letters or characters are there in the string.
Output
An array in Ruby is a collection of items. You can store multiple values like numbers, strings, or even
objects in one variable.
Output
Output
Output
Explanation: each is used to go through every item in the array and perform some action
(like printing).
Q1. What is ruby? Write the syntax to display “Welcome to Ruby Programming”.
What is Ruby?
Ruby is a high-level, interpreted, and object-oriented programming language. It is known for being
easy to read, simple to write, and very developer-friendly.
Ruby was created by Yukihiro Matsumoto in the mid-1990s in Japan. His goal was to make a
language that is fun to use and focuses on productivity and simplicity.
Automation scripts
Data processing
Command-line tools
Ruby is often praised for its clear syntax and natural flow. It reads more like English, making it easy
for beginners to learn.
Features of Ruby
3. Flexible and Powerful – You can easily change parts of the language to suit your needs.
4. Rich Libraries – Ruby comes with a lot of built-in tools to help developers.
5. Platform Independent – Ruby code can run on Windows, Linux, and Mac.
Output
Explanation:
puts stands for “put string” and is used to print something on the screen with a new line.
Ruby will show this message to the user when the program runs.
Q2. Write a note on classes, objects, types of variables, commenting style, methods,
blocks.
1. Classes in Ruby
A class is like a blueprint or template that defines how objects should behave. It can have
variables and methods inside it.
Here, my_car is an object of the Car class, and it can call the start method.
Comments are used to explain code. They are ignored during execution.
Single-line comment:
Multi-line comment:
5. Methods in Ruby
A method is a block of code that does something when called. It helps reuse code.
6. Blocks in Ruby
A block is a group of code enclosed in {} or do...end. Blocks are often used with methods like each.
In Ruby, an array is a collection of values stored together in a single variable. Arrays are used
to store multiple items like numbers, strings, or objects.
Each item in the array is stored in a position called an index, starting from 0.
Features of Arrays
Can store different types of data (e.g., numbers, strings, etc.)
Automatically grows or shrinks in size
Supports many built-in methods for easy use
How to Create an Array
There are many ways to create an array in Ruby:
1. Using square brackets []
1. if Statement
The if statement is used to run a block of code only if a condition is true.
Output
2. if-else Statement
Use else when you want to do one thing if true, and another thing if false.
Output
3. if-elsif-else Statement
Output
4. unless Statement
This is the opposite of if. It runs code only if the condition is false.
Output
5. case Statement
The case statement is like a switch in other languages. It is used when you have to compare a value
against many different options.
Output
Output
2. Exclusive Range (...)
This includes the start value, but excludes the end value.
Output
Usage of Ranges
Ranges are very useful in Ruby for many tasks like:
Looping
Conditions
Arrays
Case statements
Output
Example 2: Using Ranges in Case
Q7. Write program in ruby to generate multiplication table, odd numbers, even number,
sum of two.
Output
Q8. Write a note on ruby on rails.
What is Ruby on Rails?
Ruby on Rails (also called Rails) is a web development framework written in the Ruby
programming language. It helps developers build websites and web applications quickly
and easily.
It follows the MVC pattern – Model, View, Controller – which helps in organizing code
better.
Key Features of Ruby on Rails
1. Open Source:
Rails is free to use. You can download and start building without any cost.
2. MVC Architecture:
Rails follows the Model-View-Controller pattern which separates data, business logic,
and user interface.
3. DRY Principle (Don’t Repeat Yourself):
You write less code because Rails avoids repetition and promotes reusable code.
4. Convention Over Configuration:
Rails comes with default settings, so developers don’t need to write long setup code.
It saves time.
5. Built-in Tools:
Rails has many tools like generators, test tools, and migration tools that make
development faster.
MVC in Rails
Model – Handles the database and data-related logic (e.g., User, Product).
View – Controls what the user sees (HTML templates).
Controller – Connects models and views. It receives input and tells the model/view
what to do.
Real-Life Example
Imagine you're building an online library:
Model: Book (title, author, pages)
View: Web page showing a list of books
Controller: Gets books from the database and shows them in the view
Why Use Ruby on Rails?
Faster development
Clean and organized code
Large community for help
Good for startups and full web apps
Rails automatically creates a folder structure with many useful directories. Each folder has a
specific purpose, and this structure follows the MVC (Model-View-Controller) design
pattern.
✅ 1. app/
This is the main folder where most of your application code lives.
It has subfolders:
✅ 2. bin/
✅ 3. config/
Important files:
✅ 4. db/
Includes:
✅ 5. lib/
✅ 6. log/
Stores log files showing errors, server messages, and debug info.
✅ 7. public/
Stores static files like images, HTML pages, and error pages.
✅ 8. test/ or spec/
✅ 9. tmp/
Stores temporary files like cache and session data.
✅ 10. vendor/
Example Structure
2. Writing to a File
To write data into a file, we can use fs.writeFile() or fs.writeFileSync().
3. Deleting a File
Q2 What is NPM in Node.js? How do you install a package using NPM? How to use it
in the Node.js script?
What is NPM in Node.js?
NPM stands for Node Package Manager.
It is a tool that comes with Node.js.
It is used to install, share, and manage packages or libraries in your Node.js
project.
It allows developers to use ready-made code written by others instead of writing
everything from scratch.
Why is NPM important?
Saves time by using already available packages (like Express, Chalk, Lodash).
Helps organize project dependencies.
Makes code cleaner and reusable.
Helps keep versions under control.
Example of Popular NPM Packages
Package Purpose
This will create a file named package.json which stores details of the project and installed
packages.
Use the npm install command followed by the package name. npm install chalk
This creates a node_modules folder and updates package.json to include the package.
Now you can use the package in your JavaScript file using require().
This code uses the Chalk package to print text in blue in the terminal.
What is package.json?
Example
Step 1: Create a folder:
Output:
You will see colorful text in the terminal, styled using the Chalk package.
Q3. Discuss the working of the event-driven programming model in Node.js with
examples. (Create an event called greet and handle it to print a greeting message
using EventEmitter)
What is Event-Driven Programming in Node.js?
In Node.js, event-driven programming means that the application responds to events. These
events are like signals that something has happened, and the program takes action when
that signal is received.
Think of it like this:
Imagine you press a doorbell. That’s an event. When the bell rings, someone comes to the
door. That’s the event handler responding.
Event Something that happens (e.g., click, file loaded, user login, etc.)
Node.js is built on an asynchronous event loop. Instead of waiting for tasks to complete, it keeps
listening for events and responds when they occur.
📦 EventEmitter in Node.js
EventEmitter is a built-in Node.js module in the events library that helps you:
Advantages
Advantage Description
Real-time apps Great for chat apps, games, servers, and real-time data processing
You will see a simple form to choose a file and upload it.
Benefits
Feature Benefit
Q5. Describe the process of sending an email using Node.js and the nodemailer
package. (Write a Node.js script using nodemailer to send a welcome email.)
What is nodemailer?
nodemailer is a Node.js package that allows developers to send emails easily. It supports:
Sending emails from Gmail or other services.
HTML and text email content.
File attachments.
Steps to Send Email
1. Install nodemailer
Use npm to install the package:
2. Create a transporter
This connects to your email service (like Gmail).
3. Define mail options
This includes sender, receiver, subject, and message.
4. Send the email
Use the sendMail() function.
Example
// Load nodemailer
const nodemailer = require('nodemailer');
// Mail details
let mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Welcome to Our App!',
text: 'Hello! Thank you for joining our app. We are glad to have
you.'
};
// Send email
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log('Error:', error);
} else {
console.log('Email sent: ' + info.response);
}
});
Q6. Develop a Node.js program to perform the following operations on a MySQL table
Insert records into a table
Retrieve records using SELECT
Update records using UPDATE
Delete specific records using DELETE
Include proper error handling and use of callbacks or promises.
MySQL Table
Code
const mysql = require('mysql2');
// Insert record
con.query("INSERT INTO students (name, age) VALUES ('Priya', 20)",
(err) => {
if (err) throw err;
console.log("1 record inserted");
});
// Select records
con.query("SELECT * FROM students", (err, result) => {
if (err) throw err;
console.log("All students:", result);
});
// Update record
con.query("UPDATE students SET age = 21 WHERE name = 'Priya'", (err) =>
{
if (err) throw err;
console.log("Record updated");
});
// Delete record
con.query("DELETE FROM students WHERE name = 'Priya'", (err) => {
if (err) throw err;
console.log("Record deleted");
});
Output Example
Q7. Write a Node.js program to create a new MongoDB database and a collection
named students.
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Connect to MongoDB
client.connect((err) => {
if (err) {
console.log('Connection error:', err);
return;
}
console.log('Connected to MongoDB');
const db = client.db('mySchool');
// Create collection
db.createCollection('students', (err, res) => {
if (err) {
console.log('Error creating collection:', err);
} else {
console.log('Collection created:', res.collectionName);
}
// Close connection
client.close();
});
});
Output:
Q8. Write a Node.js script to find documents in a collection and sort them based on
one or more fields.
client.connect((err) => {
if (err) {
console.log('Connection error:', err);
return;
}
console.log('Connected to MongoDB');
const db = client.db(dbName);
const collection = db.collection('students');
client.close();
});
});
Output Example
5 Marks
Node.js is an open-source, cross-platform runtime environment that allows you to run JavaScript
code outside a browser, like on your computer or server.
It uses Google's V8 JavaScript engine (same as in Chrome browser), and it is mainly used to build
fast, scalable, and server-side applications such as web servers, APIs, and real-time chat apps.
3. Fast Execution:
Uses V8 engine to run JavaScript code very quickly.
Real-Life Example:
How to Run
Output
Summary
You can use it to build APIs, servers, tools, and real-time apps.
Q2. List any three features of Node.js. Discuss the advantages and limitations of using
Node.js for server-side development.
Three Features of Node.js
1. Asynchronous and Non-blocking I/O
o Node.js handles multiple requests at the same time without blocking the
program.
o It makes Node.js fast and suitable for real-time applications like chats, games,
and messaging apps.
2. Single-threaded with Event Loop
o Node.js uses a single thread to handle many connections by using events.
o Great for handling tasks like file uploads, data streaming, and real-time
communication.
2. Handles Many Requests
o Node.js can handle thousands of client requests at once using non-blocking
I/O.
o This is useful for building APIs and backends for mobile or web apps.
Limitations of Node.js
1. Not Good for CPU-Heavy Tasks
o Node.js is not suitable for tasks like image processing or scientific calculations.
o These tasks may block the single thread and slow down the entire app.
2. Callback Hell
o Using many nested callback functions makes the code hard to read and debug.
o It needs more tools and strict coding rules for large teams.
Q3. Write a simple program to display "Hello, Node.js!" in the terminal. (Develop and
explain a basic Node.js application that takes two numbers and prints their sum.)
// filename: sum.js
Simple Explanation
Q4. What is a module in Node.js? How do you create and use a custom module?
(Create a custom module that exports a function to calculate the factorial of a number
and use it in your main app.)
What is a Module in Node.js?
A module in Node.js is a reusable block of code whose functions and variables can be used
in other files.
Node.js has built-in modules (like fs, http, etc.)
You can also create your own custom modules.
// factorial.js
Step 2: Create another file named app.js (This is your main app)
// app.js
Output
Q5. What is the purpose of the HTTP module and URL module in Node.js?
1. HTTP Module
✅ Purpose:
The http module allows you to create web servers and handle HTTP requests and responses.
🧩 Key Uses:
Create a server
Listen to requests
Example
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
2. URL Module
✅ Purpose:
🧩 Key Uses:
Example
console.log(parsedUrl.pathname); // /home
console.log(parsedUrl.query.name); // Priya
Together:
What is NPM?
What is a Package?
A package is a folder that contains JavaScript code and a special file called package.json.
Examples of common NPM packages are:
This will:
Once a package is installed, you can use it in your Node.js code by requiring it.
In this example:
Q7. Explain the steps to connect a Node.js application with a MySQL database.
Node.js is a popular backend technology used to build fast and scalable web applications. To store
and manage data, we can connect Node.js with a database like MySQL. MySQL is a relational
database that stores data in tables.
In your project folder, open a terminal and run: npm install mysql2
This command installs the mysql2 package which helps Node.js connect and interact with
MySQL
// Create connection
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '', // use your MySQL password here
database: 'school'
});
// Connect to MySQL
con.connect((err) => {
if (err) throw err;
console.log("Connected to MySQL!");
});
Step 5: Perform Database Operations
Q8. Explain the usage of SQL clauses (WHERE, ORDER BY, LIMIT) with suitable
Node.js examples
1. WHERE Clause
2. ORDER BY Clause
The ORDER BY clause is used to sort the results in ascending (ASC) or descending (DESC) order.
// Connect to MongoDB
MongoClient.connect(url, function(err, client) {
if (err) throw err;
console.log("Connected to MongoDB!");
// Create database
const db = client.db("mySchool");
// Create collection
db.createCollection("students", function(err, res) {
if (err) throw err;
console.log("Collection 'students' created!");
client.close();
});
});
Output
Q10. Explain how the limit() method is used in MongoDB queries with Node.js.
Syntax:
const db = client.db('students');
db.collection("students").find({}).limit(3).toArray(function(err,
result){
if (err) throw err;
console.log("Top 3 Students")
console.log(result);
client.close();
});
});
Explanation:
Use Case:
Suppose your students collection has 100 entries, but you want to show only the top 3 for
performance or layout reasons. The limit(3) method is perfect for that.
✅ Conclusion:
The limit() method in MongoDB with Node.js is a simple but powerful tool to control how much data
you fetch from the database. It improves performance and makes your applications more responsive.