0% found this document useful (0 votes)
19 views70 pages

FSD Notes

The document outlines the evolution of the web from Web 1.0, which was static and read-only, to Web 2.0, which introduced user interaction and content creation, and finally to Web 3.0, which emphasizes decentralization, user ownership, and advanced technologies like AI and blockchain. It also describes the architecture of web services, including components like service providers, requestors, and registries, and discusses the importance of security in web services, highlighting standards such as HTTPS and authentication methods like OAuth. Additionally, it compares browser APIs and third-party APIs in terms of accessibility, security, and scope.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views70 pages

FSD Notes

The document outlines the evolution of the web from Web 1.0, which was static and read-only, to Web 2.0, which introduced user interaction and content creation, and finally to Web 3.0, which emphasizes decentralization, user ownership, and advanced technologies like AI and blockchain. It also describes the architecture of web services, including components like service providers, requestors, and registries, and discusses the importance of security in web services, highlighting standards such as HTTPS and authentication methods like OAuth. Additionally, it compares browser APIs and third-party APIs in terms of accessibility, security, and scope.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 70

Module 5

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.

 Websites had static pages – the content did not change.


 There was no user interaction – users could only read the information.
 Very few people could create content – only developers or companies.
 Example: Early websites like Yahoo (in the 90s), Britannica.com, and early blogs

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.

 Websites became interactive and dynamic


 Users could comment, like, share and upload content
 Use of JavaScript, CSS, AJAX, and backend programming
 Social media platforms, blogs, wikis, and e-commerce websites became popular.
 Example: Facebook, YouTube, Wikipedia, Instagram, Twitter, Amazon.

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.

 Websites understand meaning, not just keywords


 Uses decentralized networks, which means no single company controls all the data.
 Focus on user privacy and security
 Users have more control over their data and identity.
 Examples: Blockchain apps (like Ethereum DApps), AI assistants (like Siri, Alexa),
decentralized social media platforms.

Key Differences

1. Content Type

🌐 Web 1.0 – Read-only

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.

🔄 Web 2.0 – Read and Write

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

🌐 Web 1.0 – Viewer

Users were only readers. They could not change anything. There was no login or profile creation.

🔄 Web 2.0 – Creator and Viewer

Now, users can register, log in, and become content creators. YouTube videos, Instagram posts, and
blogs are created by normal users.

🤖 Web 3.0 – Owner and Controller

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

🌐 Web 1.0 – HTML, CSS

Websites were built using only HTML and basic CSS. There was no JavaScript, so everything was
simple and not interactive.

🔄 Web 2.0 – JavaScript, PHP, AJAX

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 – AI, Blockchain, ML

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

🌐 Web 1.0 – Centralized

In Web 1.0, all data and control were with the website owners or developers. Users had no control.

🔄 Web 2.0 – Centralized

Even in Web 2.0, companies like Facebook and Google control your data and can remove or track
your activity.

🤖 Web 3.0 – Decentralized

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

 Britannica.com, Early Yahoo pages, Static business websites

🔄 Web 2.0

 Facebook, YouTube, Wikipedia, Instagram

🤖 Web 3.0

 Ethereum (Blockchain platform), IPFS (decentralized file system), Brave Browser (privacy-
based), DApps (Decentralized Apps)

6. Interaction Level

🌐 Web 1.0 – Very Little

No likes, no comments, no uploads. You could only read.

🔄 Web 2.0 – High

You can interact in many ways – comment, share, like, follow, and even message others.

🤖 Web 3.0 – Smarter, Private

Interaction is more personal and secure. AI helps websites understand your needs and show you
smart suggestions.

7. Data Ownership

🌐 Web 1.0 – Website Owners

Only the website creator or company had the data. Users didn’t even have accounts.

🔄 Web 2.0 – Companies

Big companies like Google, Facebook, and Amazon store your data. They can use it to show ads or
sell to third parties.

🤖 Web 3.0 – Individual Users

Now users own their data. They use digital wallets and can decide who accesses their data. No
company can use it without permission.

Conclusion

 Web 1.0 was all about showing information.


 Web 2.0 let people interact and create content.
 Web 3.0 is about intelligence, privacy, and giving control back to users.

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.

 It is a software function or service provided over the internet


 It uses XML or JSON to exchange data
 Web Services are platform-independent and language -independent

For example, an Android app can use a web service written in Java or PHP to fetch user data from a
database.

Architecture of a Web Service

The architecture of a web service is based on three main roles:

1. Service Provider

2. Service Requestor (Client)

3. Service Registry

These parts work together using three operations:

1. Publish – The service provider registers the service in the registry

2. Find – The client searches for a service in the 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.

2. Service Requestor (Client)

 This is the system that uses the web service


 It sends a request to the service and gets the response
 The client may be a browser, mobile app, or another program
 Example: A mobile app that shows the account balance by calling the bank’s web service

3. Service Registry

 This is like a yellow pages directory for services.


 It stores information about available web services.
 The client searches here to find the needed service.
 Common protocol used: UDDI (Universal Description, Discovery, and Integration)

Technology Involved

Technology Purpose

HTTP To send requests and receive responses over the internet

XML/JSON To format the data being sent and received

SOAP A protocol to exchange messages in a standard format (XML-based)

REST A simpler, lighter protocol using HTTP methods (GET, POST, etc.)

WSDL An XML file that describes the web service and its functions

UDDI A directory where services are published and searched

🧱 How It Works: Step-by-Step Flow

1. The service provider writes a service and defines it in a WSDL file.

2. The provider registers the service with a UDDI registry.

3. The client searches the registry to find the service.

4. The client binds with the provider using SOAP or REST.

5. The client sends a request and gets a response over HTTP.

📌 Advantages of Web Services

 Language Independent – Java, Python, .NET, etc., can all talk to each other.
 Platform Independent – Works on Windows, Linux, mobile, etc.

 Reusability – The same service can be used by many applications.

 Standardized – Uses standard protocols like HTTP, SOAP, XML.

Conclusion

 Provider gives the service


 Requestor uses the service
 Registry helps connect them

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

 Open Visual Studio


 Choose Create a new project → Select ASP.NET Core Web API
 Name your project (e.g., BookAPI)
 Choose the latest .NET Core version
 Click Create

Step 2: Create a Book Model

Step 3: Create a Books Controller


Step 4: Run and Test the API

 Run the project (Press F5 or Ctrl+F5)

 Open a browser and navigate to https://localhost:{port}/api/books

 You will see the list of books in JSON format:

Explanation of HTTP Methods Used

1. GET Method

 The GET method is used to retrieve data from the server.

 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

1. What are Browser APIs?


Browser APIs are built into the web browser. They are provided by the browser itself, like Chrome,
Firefox, Edge, etc. These APIs help developers access features of the browser or device directly using
JavaScript.

📌 Examples of Browser APIs:

 Geolocation API (to get the user's location)

 DOM API (to work with HTML elements)

 Web Storage API (localStorage and sessionStorage)

 Fetch API (to send HTTP requests)

 Clipboard API (to copy or paste content)

✅ Key Points:

 No need to install anything extra.

 Safe and fast.

 Work only inside the browser.

 Cannot access data from other websites directly.

2. What are Third-party APIs?

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.

📌 Examples of Third-party APIs:

 Google Maps API (to display maps and routes)

 OpenWeatherMap API (to show weather info)

 PayPal API (for payments)

 Twitter API (to get tweets or post messages)

✅ Key Points:

 Require API keys for access.

 May need user authentication (like OAuth).

 Sometimes have rate limits.

 Provide services outside the browser.

Comparison Table: Browser API vs Third-party API


Feature Browser API Third-party API

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

Limited to browser/device Wide range of external services (weather, maps,


Scope
functionality etc.)

Speed Fast (runs on client-side) May be slower due to server requests

Dependency No outside service needed Depends on external server

Example Geolocation API Google Maps API

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.

Why Security is Important in Web Services


Security is like a lock on your door. It keeps unwanted people out and protects what’s
inside. Similarly, in web services:
 Confidentiality ensures that only the right people see the data.
 Integrity ensures that the data is not changed or tampered with.
 Authentication confirms who the user is.
 Authorization checks what the user is allowed to do.
 Non-repudiation ensures that actions cannot be denied later.
When data is shared across the internet, it passes through many networks. Hackers can try
to "sniff" the data or attack the service. That’s why developers follow standards and
security practices.

Three Common Security Standards or Practices in Web Services


1. HTTPS (HyperText Transfer Protocol Secure)

✅ What is HTTPS?

 HTTPS is the secure version of HTTP.

 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.

 Helps in confidentiality and data integrity.

✅ 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.

✅ Use in Web Services:

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?

 It checks who the user is.

 Example: Entering a username and password.

✅ What is Authorization?

 It checks what the user is allowed to do.

 Example: Some users can only view data; others can edit or delete.

✅ Common Techniques:

A. OAuth (Open Authorization):

 Used by services like Google, Facebook, etc.

 Allows one website to access your information on another site without sharing passwords.

 Example: "Login with Google" button.

B. JWT (JSON Web Tokens):

 A secure token that holds user data.

 Sent with every request after login.

 The server checks the token to allow access.

✅ Why Important?

 Stops unauthorized access.

 Makes sure only valid users are using the service.

 Protects personal or private data.

3. Input Validation and Data Filtering

✅ What is Input Validation?

 Making sure the data entered by users is safe and correct.

 Example: Only accepting numbers in a phone number field.

✅ Why It’s Needed:

 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:

 Use filters on server-side to check all input.


 Avoid trusting data from users.

 Escape special characters like <, >, ', " etc.

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

Steps Involved in Consuming a Third-Party API in a Web Application

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.

3. Make a Web Page


Create a simple HTML page with input boxes (like city name), a button, and a place to show
the results.

4. Write JavaScript Code


Use JavaScript to do things when the user clicks the button.

5. Create the API Link


Join the API’s web address, the user input, and your API key to make the full URL.

6. Send the Request


Use JavaScript to send a request to the API using the full URL.

7. Get and Read the Response


The API sends back data (usually in JSON). Read it and take out the useful info.

8. Show the Result on Page


Use JavaScript to show the data on the webpage in the right place.

9. Handle Errors
If something goes wrong (like wrong city name), show a message to the user.

10. Make It Look Good (Optional)


Use CSS to make the webpage look nice, and add loading icons if needed.

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 – The First Generation of the Web

➤ What is Web 1.0?

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.

✅ One Key Characteristic:

Static Pages – Web 1.0 had web pages that did not change unless the website owner updated them
manually.

Web 2.0 – The Social and Interactive Web

➤ What is Web 2.0?


Web 2.0 came after Web 1.0, around the early 2000s. This version allowed users to interact, create,
and share content. People could comment, like, and post their own content. It became known as the
"read-write web".

It gave rise to many popular websites like Facebook, YouTube, Wikipedia, and Instagram.

✅ One Key Characteristic:

User-Generated Content – In Web 2.0, users can create and share their own content like photos,
videos, and posts.

Web 3.0 – The Smart and Decentralized Web

➤ What is Web 3.0?

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.

It focuses on privacy, decentralization, and smart data.

✅ One Key Characteristic:

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 1.0 was simple and read-only.

 Web 2.0 allowed users to interact and create.

 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.

Example of a Browser API:

 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.

2. What are Third-Party APIs?

 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.

Example of a Third-Party API:

 Google Maps API:


This API allows developers to add interactive maps to their websites or mobile apps. For
example, a travel website can use Google Maps API to show locations, routes, and nearby
places to visitors.

Difference

Feature Browser APIs Third-Party APIs

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

Access needed No extra setup; built-in Requires API key or registration

Purpose Access browser features and device Access external services and data

Example Geolocation API Google Maps API

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.

List of Key Characteristics of Web Services

1. Interoperability

2. Loose Coupling

3. Standardized Protocols

4. Reusability

5. Discoverability

6. Statelessness

Explanation of Three Key Characteristics

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;

// Display the result on the web page


document.getElementById('weatherResult').innerText =
`Current temperature in ${city} is ${temp}°C with ${description}.`;
})
.catch(error => {
document.getElementById('weatherResult').innerText = 'Error fetching weather data.';
console.error('There was an error:', error);
});
}
</script>

</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.

3. Run the API


Run the project (F5 in Visual Studio or dotnet run in terminal). By default, it will start at
something like: https://localhost:5001

4. Test the API


Open a browser or use Postman to test:
https://localhost:5001/api/sum?a=5&b=10
You should get a JSON response like:

Q6. Compare and contrast SOAP and REST web services based on architecture, data
format, and usage.

Feature SOAP Web Services REST Web Services

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.

REST supports multiple data formats


SOAP uses only XML format for sending like JSON, XML, HTML, plain text, etc.
Data Format messages. The XML format follows a JSON is most popular because it is
strict envelope structure. lightweight and easy to use with
JavaScript.

SOAP is used in enterprise-level


applications that need high security, REST is widely used for web and
transactions, and formal contracts. It’s mobile applications because it is
Usage good for distributed enterprise lightweight, fast, and easy to use. It’s
systems, payment gateways, and good for public APIs, social media,
where standards compliance is cloud services, and web apps.
important.
Q7. Create a web api to generate multiplication table for the given number.
1. Create a new ASP.NET Core Web API project
2. Add a Controller named MultiplicationController.cs inside the Controllers folder:

3. Run the API


Run the project.
4. Test the API
Open a browser or Postman and call:
https://localhost:5001/api/multiplication?number=5
Expected JSON Response:

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.

Two Common Security Standards Used in Web Services

1. WS-Security (Web Services Security)


 What it is:
WS-Security is a standard that adds security features to SOAP-based web services.
 How it works:
It defines how to include security information like digital signatures and encryption
inside SOAP messages. This protects the messages from being read or altered by
unauthorized parties.
 Features:
o Message Integrity: Uses digital signatures to ensure the message hasn’t been
tampered with.
o Message Confidentiality: Encrypts parts of the message to keep the data
private.
o Authentication: Supports tokens like UsernameTokens or X.509 certificates
to verify identity.
 Use case:
WS-Security is widely used in enterprise environments where SOAP web services
require strict security.

2. OAuth (Open Authorization)


 What it is:
OAuth is a standard for authorization used primarily with RESTful web services.
 How it works:
OAuth allows users to grant limited access to their resources on one site (like Google
or Facebook) to another application, without sharing their passwords.
 Features:
o Uses access tokens instead of credentials for authentication.
o Supports scopes, which define what permissions the token has (e.g., read-
only or full access).
o Enables secure delegated access, meaning apps can act on behalf of a user.
 Use case:
OAuth is commonly used for login systems (like “Login with Google”) and APIs that
need to securely access user data.

Module 4 (15 Marks)


Q1. Explain the concept of Classes and Objects in Ruby with a real-world example.
Ruby is a pure object-oriented programming language. This means everything in Ruby is an
object — even numbers, strings, and nil. Ruby uses classes and objects to represent real-
world things in programming.
🧱 What is a Class?
A class is like a blueprint or template. It defines the structure and behavior of an object. A
class contains two main things:
 Attributes (data or variables)
 Methods (functions that act on the data)
You don’t use a class directly. Instead, you create objects (also called instances) based on
that class.
What is an Object?
An object is a real-world example created from a class. It has its own values for the class's
attributes and can use the class's methods.
For example, if you have a Car class, then your personal car (e.g., a red Honda City) is an
object of the Car class.
Code
Output

Why Use Classes and Objects?

 Helps organize code clearly and logically.

 Makes it easier to reuse and maintain code.

 Represents real-life things (like cars, students, books) in code.

 Encapsulation: Data and behaviour stay together in one place.

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

 Repeats as long as the condition is true.

 Starts from i = 1, and runs while i <= 10.

2. until loop

 Runs until the condition becomes true.

 Starts from j = 1, and runs until j > 10, which means from 1 to 10.

3. for loop
 Loops through a range (1..10).

 k takes each value from 1 to 10.

4. each loop

 Also goes through a range (1..10).

 n represents each value and is printed in each step.

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).

 This Post model connects to the posts table in the database.


View
 What it does: Displays data to the user.
 Where it lives: app/views
 Role: Contains HTML + Embedded Ruby (ERB) that shows content.
 Example: Shows a list of blog posts or a form to submit a new post.

 It loops through all posts and displays their titles.

Controller

 What it does: Acts as a middleman between model and view.

 Where it lives: app/controllers

 Role: Receives user input, communicates with the model, and selects the correct view.

 Example: A PostsController decides what to do when someone visits the homepage.


 This controller fetches all posts and sends them to the view to display.

How MVC Works Together (Flow)

Let’s say a user visits www.myblog.com/posts:

1. Request comes to the Controller (PostsController#index).

2. The controller calls the Model (Post.all) to get data from the database.

3. The controller passes the data (@posts) to the View.

4. The View renders HTML showing the blog posts.

5. The Response is sent to the user's browser.

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

 The module Greetings has two methods: say_hello and say_goodbye.


2. Include the Module in a Class

 We use include Greetings to add the module's methods to the Person class.
3. Create Object and Use Module Methods

Output

Explanation in Simple Words

 Module is like a container that holds useful methods.

 We include the module inside a class using include.

 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

1. Maps database tables to Ruby classes.

2. Maps table rows to objects.

3. Handles all database operations like insert, update, delete, and select using Ruby methods.

4. Automatically builds SQL queries behind the scenes.

What are Migrations?

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.

Migrations keep track of changes to the database structure over time.

 This creates a students table with name, age, and timestamp fields.
 You can run this using rails db:migrate.

Benefits of Migrations

 Easy to manage database structure.

 Can go forward (migrate) and backward (rollback).

 Migrations are written in Ruby, not SQL.


What are Associations in ActiveRecord?

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

Example: One Teacher has many Students

 Teacher model uses has_many :students


 Student model uses belongs_to :teacher

2. One-to-One Relationship

Example: One User has one Profile


3. Many-to-Many Relationship

Example: A Doctor can have many Patients, and a Patient can visit many Doctors

Example Usage of ActiveRecord with Associations

 You don’t need SQL to add a student.


 ActiveRecord handles the connection automatically.

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.

 Here, name is a string containing 5 characters.


Common String Methods in Ruby

1. upcase – Convert all letters to uppercase

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.

3. reverse – Reverse the string

Output

 Explanation: It returns the string in the opposite order.

What is an Array in Ruby?

An array in Ruby is a collection of items. You can store multiple values like numbers, strings, or even
objects in one variable.

 Here, fruits is an array with three elements.

Common Array Methods in Ruby

1. push – Add an item to the end of the array

Output

 Explanation: Adds a new number at the end of the array.


2. length – Count the number of elements

Output

 Explanation: Tells how many elements are present in the array.

3. each – Loop through each element

Output

 Explanation: each is used to go through every item in the array and perform some action
(like printing).

5 Marks Question (Module 4)

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.

Ruby is used for many purposes like:

 Web development (especially with Ruby on Rails)

 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

Here are some key features of Ruby:

1. Object-Oriented – Everything in Ruby is an object, including numbers, strings, and even


methods.

2. Simple Syntax – It’s very close to plain English.

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.

Syntax to Display a Message

In Ruby, the puts command is used to display output on the screen.

Output

Explanation:

 puts stands for “put string” and is used to print something on the screen with a new line.

 The text inside double quotes is called a string.

 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.

 This creates a class named Car with a method called start.


2. Objects in Ruby
An object is an instance of a class. When you create an object, you are using the class
template to make a real item.

 Here, my_car is an object of the Car class, and it can call the start method.

3. Types of Variables in Ruby


Type Starts With Scope Example

Local variable lowercase Inside a method or block name = "Ruby"

Instance variable @ Belongs to one object @name = "Car"

Class variable @@ Shared by all objects of a class @@count = 0

Global variable $ Can be used anywhere in the program $version = 1.0

4. Commenting Style in Ruby

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.

This block prints each number in the array.

Q3. With an example program explain how to create arrays in ruby.

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 []

2. Using the Array.new method

Example Program to Create and Use an Array


Output

Q4. Explain different type of branching construct supported by ruby.


What is a Branching Construct?
Branching constructs are used in Ruby to make decisions in a program. They allow the
program to choose different paths depending on conditions (true or false).
In simple words, branching helps the program do different things in different situations.

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

Use this when there are multiple conditions to check.

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

Q5. What are Range operators? Give an example.

What are Range Operators in Ruby?


In Ruby, a range represents a sequence of values. Range operators are used to create a set
of values that lie between a start and an end.
Ruby has two main range operators:
1. .. → Inclusive Range (includes the end value)
2. ... → Exclusive Range (does not include the end value)

Types of Range Operators


1. Inclusive Range (..)
This includes both the start and end values.

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

Example 1: Using Ranges in a Loop

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

Q9. Write the Directory structure of ruby on rails framework.


When you create a new Rails application using the command:

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:

 models/: All model files (data and database logic) go here.


 views/: All HTML templates (what users see) go here.

 controllers/: All controller files (connect views and models) go here.

 helpers/: Helper methods for views.

 assets/: JavaScript, CSS, and image files.

 jobs/: Background jobs.

 mailers/: Code to send emails.

✅ 2. bin/

 Contains small scripts to help run the application.

 Example: rails command, server start command, etc.

✅ 3. config/

 Stores all the configuration files.

 Important files:

o routes.rb: Defines application routes (URLs).

o database.yml: Database settings.

o environment.rb: Loads the app and settings.

✅ 4. db/

 Contains database-related files.

 Includes:

o migrate/ folder: Stores migration files to modify database tables.

o seeds.rb: Add default data to your database.

✅ 5. lib/

 Stores custom code and libraries created by the developer.

✅ 6. log/

 Stores log files showing errors, server messages, and debug info.

✅ 7. public/

 Stores static files like images, HTML pages, and error pages.

 Files here can be accessed directly by users.

✅ 8. test/ or spec/

 Contains test files to check if your code is working properly.

✅ 9. tmp/
 Stores temporary files like cache and session data.

✅ 10. vendor/

 Stores third-party libraries (like gems or plugins) used in your application.

Example Structure

Q10. Write a note on controllers, routers, scaffolding, view, active records.

Leaving this question

Module 3 (15 Marks)


Q1. Describe how to perform file operations (read, write, delete) using the File System
module in Node.js. (Write a Node.js program that reads the contents of a file and
prints it to the console.)
File Operations in Node.js Using the File System (fs) Module
In Node.js, file operations like reading, writing, and deleting files can be done using the
File System module, also known as the fs module. This module comes with Node.js by
default, so we don’t need to install it separately.
To use it, we first need to import it using:

1. Reading from a File


To read a file, we use the fs.readFile() or fs.readFileSync() method.

2. Writing to a File
To write data into a file, we can use fs.writeFile() or fs.writeFileSync().

3. Deleting a File

To delete a file, we use fs.unlink() or fs.unlinkSync().

Read File and Print to Console


Steps to Test:

1. Create a text file named example.txt.

2. Add some text like:


"Hello, this is a file created for testing read operation in Node.js."

3. Save the JavaScript code in a file readFile.js.

4. Run the file using the command: node readFile.js

5. Output will display the content of example.txt.

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

express Build web servers

chalk Style terminal text (colors)

nodemon Auto-restarts app during changes

mongoose Connect to MongoDB easily

How to Install a Package using NPM

Step 1: Initialize NPM in your project folder

Open terminal and run: npm init -y

 This will create a file named package.json which stores details of the project and installed
packages.

Step 2: Install a Package

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.

Step 3: Use the Package in Your Script

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?

It is a special file created by NPM that contains:

 Project name, version, description.

 List of dependencies (packages).

 Scripts to run commands.

Example
Step 1: Create a folder:

Step 2: Initialize NPM

Step 3: Install Chalk

Step 4: Create a file app.js

Step 5: Run the file

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.

Key Concepts of Event-Driven Programming


Concept Meaning

Event Something that happens (e.g., click, file loaded, user login, etc.)

EventEmitter A module in Node.js used to create and handle custom events

Event Handler A function that runs when a specific event occurs

How Node.js Uses Event-Driven Model

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.

📌 Example Use Cases:

 A user requests a webpage → “request” event is triggered.

 A file finishes loading → “loaded” event is triggered.

 A message is received → “message” event is triggered.

📦 EventEmitter in Node.js

EventEmitter is a built-in Node.js module in the events library that helps you:

 Create your own custom events

 Add listeners (handlers) for those events

 Emit (trigger) those events when needed

Steps to Use EventEmitter

1. Import the events module.

2. Create an EventEmitter object.

3. Create an event handler (function).

4. Bind the event with the handler.

5. Emit the event when needed.

Advantages

Advantage Description

Asynchronous handling Program doesn't wait; continues doing other tasks

Scalability Handles many users efficiently without slowing down

Cleaner code Separates logic for each event, improving readability

Real-time apps Great for chat apps, games, servers, and real-time data processing

Example: Create and Handle a "greet" Event


Q4. Explain how to upload files using Node.js package. (Create a simple Node.js app
that allows uploading a file and saves it on the server.)

What is File Upload in Node.js?


File upload means allowing users to select a file (like an image, PDF, or document) from
their device and send it to the server, where it will be stored in a folder.
In Node.js, we can easily handle file uploads using a package called multer.
Why Use multer?
 multer is a Node.js middleware that helps handle multipart/form-data, which is the
encoding used when uploading files via forms.
 It helps store files to a folder or in memory.
 It is easy to set up and use with Express.js.
Steps to Upload Files in Node.js
Step 1: Setup Your Project
Open your terminal and create a project folder:

Step 2: Install Required Packages


Install Express and Multer:

Step 3: Create app.js File


Now create a file called app.js and write the following code:

Step 5: Create Upload Folder

Create a folder named uploads in your project root:

 This is where all uploaded files will be stored.

Step 6: Run Your App

Start your server: node app.js

Open your browser and go to: http://localhost:3000

You will see a simple form to choose a file and upload it.

What Happens When You Upload?

 You choose a file.

 The form sends it to the route /upload.

 multer processes the file and stores it in the uploads/ folder.

 You see a success message with the filename.

Benefits
Feature Benefit

Easy setup Only a few lines of code

File control You can limit file types and sizes

Good performance Multer is fast and memory-efficient

Folder storage Files are saved locally on the server

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');

// Create transporter for Gmail


let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]', // your Gmail
pass: 'abcd efgh ijkl mnop' // your password or app password
}
});

// 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');

const con = mysql.createConnection({


host: 'localhost',
user: 'root',
password: '',
database: 'school'
});

// 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.

const { MongoClient } = require('mongodb');

// 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.

const { MongoClient } = require('mongodb');

// MongoDB connection URL


const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

// Database and collection


const dbName = 'mySchool';

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');

// Find and sort by age in ascending order


collection.find().sort({ age: 1 }).toArray((err, result) => {
if (err) {
console.log('Error fetching data:', err);
} else {
console.log('Sorted Students by Age:');
console.log(result);
}

client.close();
});
});

Output Example
5 Marks

Q1. What is Node.js? Explain with an example program to display “Welcome to


Node.js”.
What is Node.js?

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.

Key Features of Node.js:

1. Asynchronous & Non-blocking:


Node.js handles many requests at the same time without waiting for one to finish.

2. Single-threaded Event Loop:


It uses one thread for handling multiple client requests, which makes it fast and lightweight.

3. Fast Execution:
Uses V8 engine to run JavaScript code very quickly.

4. NPM (Node Package Manager):


It comes with NPM to install and manage open-source packages.

Real-Life Example:

Save file as welcome.js

How to Run

Follow these steps to run the program:

1. Install Node.js from: https://nodejs.org

2. Open Command Prompt or Terminal.

3. Navigate to the folder where welcome.js is saved.

4. Run this command: node welcome.js

Output

Summary

 Node.js is used to run JavaScript on the server side.

 It is fast, event-driven, and non-blocking.

 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 This helps in saving memory and managing many users easily.

3. Cross-platform and Open Source


o Node.js works on Windows, Mac, and Linux.

o It is open-source, so developers can use it for free and contribute to its


development.

Advantages of Node.js for Server-side Development


1. Fast Performance
o Uses Google’s V8 engine, which compiles JavaScript code quickly.

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.

3. Large Ecosystem of Modules


o Comes with NPM (Node Package Manager) which offers thousands of free
packages.
o Saves time and helps developers add extra features easily.

4. Same Language for Frontend and Backend


o Developers can use JavaScript on both client and server sides.

o This makes development faster and easier for full-stack 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 Although Promises and async/await help reduce this problem.

3. Less Mature in Enterprise Applications

o Compared to Java or .NET, Node.js is still new in enterprise-level projects.

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

// Get user input from command-line arguments


const num1 = parseFloat(process.argv[2]);
const num2 = parseFloat(process.argv[3]);

// Add the numbers


const sum = num1 + num2;

// Print the results


console.log("Hello, Node.js!");
console.log(`The sum of ${num1} and ${num2} is ${sum}`);

Simple Explanation

 process.argv[2] is the first input (after filename)

 process.argv[3] is the second input

 parseFloat() converts string to number

 console.log() prints the output

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.

Why Use Modules?


 Helps organize code
 Makes code reusable
 Keeps the code clean and modular

How to Create and Use a Custom Module

Step 1: Create a file named factorial.js (This is your custom module)

// factorial.js

// Define and export a function to calculate factorial


function findFactorial(n) {
if (n === 0 || n === 1) return 1;
return n * findFactorial(n - 1);
}

// Export the function


module.exports = findFactorial;

Step 2: Create another file named app.js (This is your main app)

// app.js

// Import the custom module


const factorial = require('./factorial');

// Use the module


const num = 5;
console.log(`Factorial of ${num} is: ${factorial(num)}`);

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

 Send back responses (HTML, JSON, etc.)

Example

const http = require('http');

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


res.write('Hello from HTTP Module');
res.end();
});

server.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
2. URL Module

✅ Purpose:

The url module helps parse and handle URLs easily.

🧩 Key Uses:

 Break a URL into parts (protocol, host, pathname, query, etc.)

 Extract and use query parameters

Example

const url = require('url');

const myURL = 'http://localhost:3000/home?name=Priya&age=20';


const parsedUrl = url.parse(myURL, true);

console.log(parsedUrl.pathname); // /home
console.log(parsedUrl.query.name); // Priya
Together:

These modules are often used together to:

 Build HTTP servers

 Handle requests based on the URL

 Access query parameters in web apps


Q6. Discuss about NPM in Node.js. How do you install a package using NPM?
How to use it in the Node.js script?

What is NPM?

NPM stands for Node Package Manager.


It is the official package manager for Node.js. It helps developers to:

 Download and use code written by others (called packages or modules)

 Share their own code with others

 Manage project dependencies (libraries your project needs to work)

NPM is installed automatically when you install Node.js.

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:

 express – to build web servers

 mongoose – to work with MongoDB

 nodemailer – to send emails

 chalk – to color terminal text

How to Install a Package?

To install a package, use the npm install command:

Example: npm install chalk

This will:

 Download the chalk package from the internet

 Add it to the node_modules folder

 Add it to dependencies in package.json

How to Use Installed Package in Node.js?

Once a package is installed, you can use it in your Node.js code by requiring it.

Example (using chalk):

// Use chalk to color text in terminal


const chalk = require('chalk');

console.log(chalk.blue('Hello from Chalk!'));

In this example:

 require('chalk') loads the package


 chalk.blue() makes the text blue in the terminal

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.

To connect Node.js with MySQL, we use a special package called mysql2.

Steps to Connect Node.js with MySQL

Step 1: Install MySQL on Your System

Make sure MySQL Server is installed on your computer.

Step 2: Install the MySQL Package in Node.js

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

Step 3: Create a Database in MySQL

Use your MySQL client to create a database

CREATE DATABASE school;

CREATE TABLE students (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
age INT
);

Step 4: Create a Node.js File and Connect to MySQL

Create a file named app.js and write the following code:

const mysql = require('mysql2');

// 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

con.query("SELECT * FROM students", (err, result) => {


if (err) throw err;
console.log(result);
});

Q8. Explain the usage of SQL clauses (WHERE, ORDER BY, LIMIT) with suitable
Node.js examples

1. WHERE Clause

The WHERE clause is used to filter records based on a condition.

Example: Get all students who are 20 years old.

const mysql = require('mysql2');

const con = mysql.createConnection({


host: 'localhost',
user: 'root',
password: '',
database: 'school'
});
con.connect((err) => {
if (err) throw err;
con.query("SELECT * FROM students WHERE age = 20", (err, result) => {
if (err) throw err;
console.log("Students aged 20:", result);
});
});

2. ORDER BY Clause

The ORDER BY clause is used to sort the results in ascending (ASC) or descending (DESC) order.

Example: Get all students sorted by age in descending order.

con.query("SELECT * FROM students ORDER BY age DESC", (err, result) =>


{
if (err) throw err;
console.log("Students sorted by age:", result);
});
3. LIMIT Clause

The LIMIT clause is used to specify the number of records to return.

Example: Get only the first 2 students from the table.


con.query("SELECT * FROM students LIMIT 2", (err, result) => {
if (err) throw err;
console.log("First 2 students:", result);
});
Q9. Write a Node.js program to create a new MongoDB database and a collection
named students.

const { MongoClient } = require('mongodb');

// MongoDB connection URL


const url = "mongodb://localhost:27017";

// 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.

Purpose of limit() in Node.js MongoDB Queries:

 Controls the size of result sets.

 Improves performance by avoiding large data loads.

 Commonly used for pagination and dashboards.

Syntax:

Example: Show Top 3 Students from students Collection

const {MongoClient} = require('mongodb')


const url = "mongodb://localhost:27017"

MongoClient.connect(url, function(err, client){


if (err) throw err;
console.log("MongDB Connected Successfully!");

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:

 find({}): Finds all documents in the students collection.

 .limit(3): Limits the result to 3 documents only.

 .toArray(): Converts the result into an array and prints it.

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.

Module 2 (15 Marks)

You might also like