0% found this document useful (0 votes)
38 views

SDC Manual With Outputs

Uploaded by

n46688019
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)
38 views

SDC Manual With Outputs

Uploaded by

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

Program 1: Build a responsive web application for shopping cart with registration, login,

catalog and cart pages using CSS3 features, flex and grid.
Code:

Home.html
<section class="flex-item">
<h2>Welcome to Our Shopping Cart App!</h2>
<p>
This is a simple shopping cart web application where you can explore our catalog of products,
add items to your cart, and proceed to checkout.
</p>
<p>
Whether you're looking for electronics, clothing, accessories, or more, we have a wide selection
of products to choose from.
</p>
<p>
Get started by browsing our catalog or log in to view your cart and place an order.
</p>
</section>
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shopping Cart App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Shopping Cart App</h1>
<nav>
<ul>
<li><a href="home.html">Home</a></li>
<li><a href="catalog.html">Catalog</a></li>
<li><a href="cart.html">Cart</a></li>
<li><a href="login.html">Login</a></li>
<li><a href="register.html">Register</a></li>
</ul>
</nav>
</header>
<main id="main-content">
<!-- Content will be loaded dynamically -->
</main>
<script src="script.js"></script>
</body>
</html>
Login.html
<section>
<h2>Login</h2>
<form id="login-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<button type="submit">Login</button>
</form>
</section>

Register.html
<section>
<h2>Registration</h2>
<form id="registration-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<button type="submit">Register</button>
</form>
</section>

Cart.html
<section>
<h2>Cart</h2>
<div class="cart-item">
<img src="images\product1.jpg" alt="1roduct 1">
<h3>Product 1</h3>
<p>Description of Product 1.</p>
<p>Price: $10</p>
<button>Remove</button>
</div>
<div class="cart-item">
<img src="images\product1.jpg" alt="Product 2">
<h3>Product 2</h3>
<p>Description of Product 2.</p>
<p>Price: $15</p>
<button>Remove</button>
</div>
<!-- Add more cart items here -->
<button>Checkout</button>
</section>
Catalog.html
<section>
<h2>Catalog</h2>
<div class="product">
<img src="images\product1.jpg" alt="Product 1">
<h3>Product 1</h3>
<p>Description of Product 1.</p>
<button>Add to Cart</button>
</div>
<div class="product">
<img src="images\product1.jpg" alt="Product 2">
<h3>Product 2</h3>
<p>Description of Product 2.</p>
<button>Add to Cart</button>
</div>
<div class="product">
<img src="images\product1.jpg" alt="Product 1">
<h3>Product 1</h3>
<p>Description of Product 1.</p>
<button>Add to Cart</button>
</div>
<div class="product">
<img src="images\product1.jpg" alt="Product 2">
<h3>Product 2</h3>
<p>Description of Product 2.</p>
<button>Add to Cart</button>
</div>
<!-- Add more products here -->
</section>
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shopping Cart App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Shopping Cart App</h1>
<nav>
<ul>
<li><a href="home.html">Home</a></li>
<li><a href="catalog.html">Catalog</a></li>
<li><a href="cart.html">Cart</a></li>
<li><a href="login.html">Login</a></li>
<li><a href="register.html">Register</a></li>
</ul>
</nav>
</header>
<main id="main-content">
<!-- Content will be loaded dynamically -->
</main>
<script src="script.js"></script>
</body>
</html>
Script.js
document.addEventListener("DOMContentLoaded", function () {
const homeLink = document.getElementById("home-link");
const catalogLink = document.getElementById("catalog-link");
const cartLink = document.getElementById("cart-link");
const mainContent = document.getElementById("main-content");

homeLink.addEventListener("click", function () {
setActiveLink(homeLink);
loadContent("home.html");
});

catalogLink.addEventListener("click", function () {
setActiveLink(catalogLink);
loadContent("catalog.html");
});

cartLink.addEventListener("click", function () {
setActiveLink(cartLink);
loadContent("cart.html");
});

function setActiveLink(activeLink) {
const links = [homeLink, catalogLink, cartLink];
links.forEach(link => {
link.classList.remove("active");
});
activeLink.classList.add("active");
}

function loadContent(page) {
fetch(page)
.then(response => response.text())
.then(html => {
mainContent.innerHTML = html;
});
}

Style.css
/* Reset default margin and padding */
body, h1, h2, h3, ul, li {
margin: 0;
padding: 0;
}

/* Basic styling */
header {
background-color: #333;
color: white;
padding: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}

nav ul {
list-style-type: none;
display: flex;
}

nav ul li {
margin-right: 20px;
}

nav ul li a {
color: white;
text-decoration: none;
}

.flex-item {
background-color: #3498db; /* Blue background color */
color: white; /* Text color */
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
max-width: 600px;
margin: 0 auto;
}

main {
padding: 20px;
display: grid;
grid-template-columns: 1fr;
grid-gap: 20px;
}

Program 2: Make a simple web application responsive web application using


Bootstrap framework, VS code
To create a simple responsive web application using the Bootstrap framework in Visual Studio Code,
follow these steps:
Setup Your Development Environment:
Install Visual Studio Code from here.
Make sure you have Node.js installed on your system. You can download it from here.
Create a New Project:
Open Visual Studio Code.
Create a new folder for your project and open it in Visual Studio Code.
Open a terminal in Visual Studio Code (Ctrl + `) and initialize a new npm project by running:
npm init -y
Install Bootstrap and its dependencies by running:
npm install bootstrap jquery popper.js
Create HTML File:
Create a new HTML file in your project folder, for example index.html.
Add the basic structure of an HTML file and link Bootstrap's CSS file in the <head> section:
Indexbootstrap.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Bootstrap App</title>
<link href="node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<!-- Your content goes here -->
<h1>Hello, Bootstrap!</h1>
</div>
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/popper.js/dist/umd/popper.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
</body>
</html>

Home.html
<section class="flex-item">
<h2>Welcome to Our Shopping Cart App!</h2>
<p>
This is a simple shopping cart web application where you can explore our catalog of products,
add items to your cart, and proceed to checkout.
</p>
<p>
Whether you're looking for electronics, clothing, accessories, or more, we have a wide selection
of products to choose from.
</p>
<p>
Get started by browsing our catalog or log in to view your cart and place an order.
</p>
</section>
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shopping Cart App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Shopping Cart App</h1>
<nav>
<ul>
<li><a href="home.html">Home</a></li>
<li><a href="catalog.html">Catalog</a></li>
<li><a href="cart.html">Cart</a></li>
<li><a href="login.html">Login</a></li>
<li><a href="register.html">Register</a></li>
</ul>
</nav>
</header>
<main id="main-content">
<!-- Content will be loaded dynamically -->
</main>
<script src="script.js"></script>
</body>
</html>
Login.html
<section>
<h2>Login</h2>
<form id="login-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<button type="submit">Login</button>
</form>
</section>

Register.html
<section>
<h2>Registration</h2>
<form id="registration-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<button type="submit">Register</button>
</form>
</section>

Cart.html
<section>
<h2>Cart</h2>
<div class="cart-item">
<img src="images\product1.jpg" alt="1roduct 1">
<h3>Product 1</h3>
<p>Description of Product 1.</p>
<p>Price: $10</p>
<button>Remove</button>
</div>
<div class="cart-item">
<img src="images\product1.jpg" alt="Product 2">
<h3>Product 2</h3>
<p>Description of Product 2.</p>
<p>Price: $15</p>
<button>Remove</button>
</div>
<!-- Add more cart items here -->
<button>Checkout</button>
</section>
Catalog.html
<section>
<h2>Catalog</h2>
<div class="product">
<img src="images\product1.jpg" alt="Product 1">
<h3>Product 1</h3>
<p>Description of Product 1.</p>
<button>Add to Cart</button>
</div>
<div class="product">
<img src="images\product1.jpg" alt="Product 2">
<h3>Product 2</h3>
<p>Description of Product 2.</p>
<button>Add to Cart</button>
</div>
<div class="product">
<img src="images\product1.jpg" alt="Product 1">
<h3>Product 1</h3>
<p>Description of Product 1.</p>
<button>Add to Cart</button>
</div>
<div class="product">
<img src="images\product1.jpg" alt="Product 2">
<h3>Product 2</h3>
<p>Description of Product 2.</p>
<button>Add to Cart</button>
</div>
<!-- Add more products here -->
</section>
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shopping Cart App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Shopping Cart App</h1>
<nav>
<ul>
<li><a href="home.html">Home</a></li>
<li><a href="catalog.html">Catalog</a></li>
<li><a href="cart.html">Cart</a></li>
<li><a href="login.html">Login</a></li>
<li><a href="register.html">Register</a></li>
</ul>
</nav>
</header>
<main id="main-content">
<!-- Content will be loaded dynamically -->
</main>
<script src="script.js"></script>
</body>
</html>
Script.js
document.addEventListener("DOMContentLoaded", function () {
const homeLink = document.getElementById("home-link");
const catalogLink = document.getElementById("catalog-link");
const cartLink = document.getElementById("cart-link");
const mainContent = document.getElementById("main-content");

homeLink.addEventListener("click", function () {
setActiveLink(homeLink);
loadContent("home.html");
});

catalogLink.addEventListener("click", function () {
setActiveLink(catalogLink);
loadContent("catalog.html");
});

cartLink.addEventListener("click", function () {
setActiveLink(cartLink);
loadContent("cart.html");
});

function setActiveLink(activeLink) {
const links = [homeLink, catalogLink, cartLink];
links.forEach(link => {
link.classList.remove("active");
});
activeLink.classList.add("active");
}

function loadContent(page) {
fetch(page)
.then(response => response.text())
.then(html => {
mainContent.innerHTML = html;
});
}

Style.css
/* Reset default margin and padding */
body, h1, h2, h3, ul, li {
margin: 0;
padding: 0;
}

/* Basic styling */
header {
background-color: #333;
color: white;
padding: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}

nav ul {
list-style-type: none;
display: flex;
}

nav ul li {
margin-right: 20px;
}

nav ul li a {
color: white;
text-decoration: none;
}

.flex-item {
background-color: #3498db; /* Blue background color */
color: white; /* Text color */
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
max-width: 600px;
margin: 0 auto;
}

main {
padding: 20px;
display: grid;
grid-template-columns: 1fr;
grid-gap: 20px;
}

Run Your Application:


You can use a local server to run your application. One simple way to do this is by using the live-
server npm package. Install it globally by running:
npm install -g live-server
Then, navigate to your project folder in the terminal and run:
live-server
This command will start a local development server and open your web application in the default web
browser.
After running the server make sure to copy paste your responsive shopping application we created to
the current running folder.

Program 3: Use JavaScript for doing client – side validation of the pages implemented in the
above program
To implement client-side validation for the login and registration forms using JavaScript, you can add
event listeners to the form submit events. Modify your existing code in script.js to include validation
for the login and registration forms:
Create a New Project:
Open Visual Studio Code.
Create a new folder for your project and open it in Visual Studio Code.
Open a terminal in Visual Studio Code (Ctrl + `) and initialize a new npm project by running:
npm init -y
Install Bootstrap and its dependencies by running:
npm install bootstrap jquery popper.js

Code:
Script.js
document.addEventListener("DOMContentLoaded", function () {
const homeLink = document.getElementById("home-link");
const catalogLink = document.getElementById("catalog-link");
const cartLink = document.getElementById("cart-link");
const mainContent = document.getElementById("main-content");

homeLink.addEventListener("click", function () {
setActiveLink(homeLink);
loadContent("home.html");
});

catalogLink.addEventListener("click", function () {
setActiveLink(catalogLink);
loadContent("catalog.html");
});

cartLink.addEventListener("click", function () {
setActiveLink(cartLink);
loadContent("cart.html");
});

// Login form validation


const loginForm = document.getElementById("login-form");
loginForm.addEventListener("submit", function (event) {
event.preventDefault(); // Prevent form submission
const username = loginForm.elements["username"].value.trim();
const password = loginForm.elements["password"].value.trim();

if (!username || !password) {
alert("Please enter both username and password.");
return;
}

// Proceed with login logic if validation passes


// For demonstration purposes, you can simply log the credentials
console.log("Username:", username);
console.log("Password:", password);

// You can also redirect to a login API or perform further actions here
});

// Registration form validation


const registrationForm = document.getElementById("registration-form");
registrationForm.addEventListener("submit", function (event) {
event.preventDefault(); // Prevent form submission
const username = registrationForm.elements["username"].value.trim();
const email = registrationForm.elements["email"].value.trim();
const password = registrationForm.elements["password"].value.trim();

if (!username || !email || !password) {


alert("Please fill in all fields.");
return;
}

// Proceed with registration logic if validation passes


// For demonstration purposes, you can simply log the data
console.log("Username:", username);
console.log("Email:", email);
console.log("Password:", password);

// You can also redirect to a registration API or perform further actions here
});

function setActiveLink(activeLink) {
const links = [homeLink, catalogLink, cartLink];
links.forEach(link => {
link.classList.remove("active");
});
activeLink.classList.add("active");
}

function loadContent(page) {
fetch(page)
.then(response => response.text())
.then(html => {
mainContent.innerHTML = html;
});
}
});
Indexbootstrap.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Bootstrap App</title>
<link href="node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<!-- Your content goes here -->
<h1>Hello, Bootstrap!</h1>
</div>
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/popper.js/dist/umd/popper.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
</body>
</html>

Home.html
<section class="flex-item">
<h2>Welcome to Our Shopping Cart App!</h2>
<p>
This is a simple shopping cart web application where you can explore our catalog of products,
add items to your cart, and proceed to checkout.
</p>
<p>
Whether you're looking for electronics, clothing, accessories, or more, we have a wide selection
of products to choose from.
</p>
<p>
Get started by browsing our catalog or log in to view your cart and place an order.
</p>
</section>
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shopping Cart App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Shopping Cart App</h1>
<nav>
<ul>
<li><a href="home.html">Home</a></li>
<li><a href="catalog.html">Catalog</a></li>
<li><a href="cart.html">Cart</a></li>
<li><a href="login.html">Login</a></li>
<li><a href="register.html">Register</a></li>
</ul>
</nav>
</header>
<main id="main-content">
<!-- Content will be loaded dynamically -->
</main>
<script src="script.js"></script>
</body>
</html>

Login.html
<section>
<h2>Login</h2>
<form id="login-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<button type="submit">Login</button>
</form>
</section>
Register.html
<section>
<h2>Registration</h2>
<form id="registration-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<button type="submit">Register</button>
</form>
</section>

Cart.html
<section>
<h2>Cart</h2>
<div class="cart-item">
<img src="images\product1.jpg" alt="1roduct 1">
<h3>Product 1</h3>
<p>Description of Product 1.</p>
<p>Price: $10</p>
<button>Remove</button>
</div>
<div class="cart-item">
<img src="images\product1.jpg" alt="Product 2">
<h3>Product 2</h3>
<p>Description of Product 2.</p>
<p>Price: $15</p>
<button>Remove</button>
</div>
<!-- Add more cart items here -->
<button>Checkout</button>
</section>

Catalog.html
<section>
<h2>Catalog</h2>
<div class="product">
<img src="images\product1.jpg" alt="Product 1">
<h3>Product 1</h3>
<p>Description of Product 1.</p>
<button>Add to Cart</button>
</div>
<div class="product">
<img src="images\product1.jpg" alt="Product 2">
<h3>Product 2</h3>
<p>Description of Product 2.</p>
<button>Add to Cart</button>
</div>
<div class="product">
<img src="images\product1.jpg" alt="Product 1">
<h3>Product 1</h3>
<p>Description of Product 1.</p>
<button>Add to Cart</button>
</div>
<div class="product">
<img src="images\product1.jpg" alt="Product 2">
<h3>Product 2</h3>
<p>Description of Product 2.</p>
<button>Add to Cart</button>
</div>
<!-- Add more products here -->
</section>

Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shopping Cart App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Shopping Cart App</h1>
<nav>
<ul>
<li><a href="home.html">Home</a></li>
<li><a href="catalog.html">Catalog</a></li>
<li><a href="cart.html">Cart</a></li>
<li><a href="login.html">Login</a></li>
<li><a href="register.html">Register</a></li>
</ul>
</nav>
</header>
<main id="main-content">
<!-- Content will be loaded dynamically -->
</main>
<script src="script.js"></script>
</body>
</html>
Style.css
/* Reset default margin and padding */
body, h1, h2, h3, ul, li {
margin: 0;
padding: 0;
}

/* Basic styling */
header {
background-color: #333;
color: white;
padding: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}

nav ul {
list-style-type: none;
display: flex;
}

nav ul li {
margin-right: 20px;
}

nav ul li a {
color: white;
text-decoration: none;
}

.flex-item {
background-color: #3498db; /* Blue background color */
color: white; /* Text color */
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
max-width: 600px;
margin: 0 auto;
}

main {
padding: 20px;
display: grid;
grid-template-columns: 1fr;
grid-gap: 20px;
}

Run Your Application:


You can use a local server to run your application. One simple way to do this is by using the live-
server npm package. Install it globally by running:
npm install -g live-server
Then, navigate to your project folder in the terminal and run:
live-server
This command will start a local development server and open your web application in the default web
browser.
After running the server make sure to copy paste your responsive shopping application we created to
the current running folder.

Program 4: Explore the features of ES6 like arrow functions, callbacks, promises, async/await.
Implement an application for reading the weather information from openweathermap.org and
display the information in the form of a graph on the web page
Index.js
const express = require('express');
const request = require('request');
const path = require('path'); // Add this line
const app = express();
const apiKey = '10ebba3a581ae9a59e8a7693271a4969'; // Replace with your OpenWeatherMap API
key

// Set EJS as the view engine


app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

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


const latitude = req.query.lat || '44.34';
const longitude = req.query.lon || '10.99';

const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=$


{longitude}&appid=${apiKey}`;

request(url, (error, response, body) => {


if (error || response.statusCode !== 200) {
return res.send('Error fetching weather data');
}

const data = JSON.parse(body);


const temp = data.main.temp - 273.15; // Convert Kelvin to Celsius
const weather = data.weather[0].main;

const chartData = {
labels: ['Temperature'],
datasets: [{
label: weather,
data: [temp.toFixed(2)],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
}]
};

res.render('index', { chartData }); // Pass chart data to the template


});
});

app.listen(3000, () => console.log('Server listening on port 3000'));


index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather</title>
</head>
<body>
<h1>Weather Information</h1>
<p>Temperature: <%= chartData.datasets[0].data[0] %>°C</p>
<p>Weather: <%= chartData.datasets[0].label %></p>
</body>
</html>
Run Your Application:
npm init –y
npm install express request ejs
node index.js
Program 6: Create an xml for the bookstore. Validate the same using both DTD and XSD
Bookstore.dtd
<!ELEMENT bookstore (book+)>
<!ELEMENT book (title, author, year, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT price (#PCDATA)>

Bookstore.xsd
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="bookstore">
<xs:complexType>
<xs:sequence>
<xs:element name="book" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="year" type="xs:integer"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:schema>

Bookstore.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE bookstore SYSTEM "bookstore.dtd">
<bookstore xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="bookstore.xsd">
<book>
<title>Harry Potter and the Philosopher's Stone</title>
<author>J.K. Rowling</author>
<year>1997</year>
<price>20.00</price>
</book>
<book>
<title>The Hobbit</title>
<author>J.R.R. Tolkien</author>
<year>1937</year>
<price>15.00</price>
</book>
</bookstore>
Program 8: Maintaining the transactional history of any user is very important. Explore the
various session tracking mechanism (Cookies, HTTP Session)
Server.js
// Setting a cookie in Express.js
const express = require('express');
const app = express();
app.get('/set-cookie', (req, res) => {
res.cookie('username', 'john_doe', { maxAge: 900000, httpOnly: true });
res.send('Cookie has been set');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

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


res.send('Hello, World!');
});

// Retrieving a cookie in Express.js


app.get('/get-cookie', (req, res) => {
const username = req.cookies.username;
res.send(`Username: ${username}`);
});

const session = require('express-session');

// Setup session middleware


app.use(session({
secret: 'my_secret_key',
resave: false,
saveUninitialized: true
}));
// Setting session data
app.get('/set-session', (req, res) => {
req.session.username = 'john_doe';
res.send('Session has been set');
});

// Retrieving session data


app.get('/get-session', (req, res) => {
const username = req.session.username;
res.send(`Username: ${username}`);
});

Run the application:


npm init -y
npm install express
npm install express cookie-parser express-session
npm install express-session
node server.js

Program 9:Create a custom server using http module and explore the other modules of Node
JS like OS path, event in Vs code
Server.js
// Importing required modules
const http = require('http');

// Creating a server
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World!\n');
});

// Listening on port 3000


server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Os.js
const os = require('os');
console.log('Platform:', os.platform());
console.log('Architecture:', os.arch());
console.log('Total memory (bytes):', os.totalmem());
console.log('Free memory (bytes):', os.freemem());
console.log('CPU Information:', os.cpus());
Path.js
const path = require('path');

const filePath = '/path/to/some/file.txt';

console.log('File Name:', path.basename(filePath));


console.log('Directory Name:', path.dirname(filePath));
console.log('File Extension:', path.extname(filePath));
Events.js
const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();

myEmitter.on('event', () => {
console.log('An event occurred!');
});

myEmitter.emit('event');
Run this application:
In terminal type the following command:
node server.js
Open a web browser and go to http://localhost:3000 to see the "Hello World!" message served
by your custom server.

Program 10: Develop an express web application that can interact with REST API to perform
CRUD operations on student data. (Use Postman)
STEPS TO FOLLOW: To perform CRUD (Create, Read, Update, Delete) operations on student data.
We'll use Postman to test the API endpoints.
First, make sure you have Node.js and npm installed on your system. Then, follow these steps:
Create a new directory for your project:
Open your terminal or command prompt and create a new directory for your project:
mkdir express-student-api
Navigate into the project directory:
cd express-student-api
Initialize a new Node.js project:
Run the following command to create a package.json file
npm init -y
Install Express.js:
Install Express.js as a dependency for your project:
npm install express
Create your main application file:
Create a new file named app.js and add the following code:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

// Middleware to parse JSON bodies


app.use(express.json());

// Temporary in-memory data store


let students = [];

// Routes
app.get('/students', (req, res) => {
res.json(students);
});

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


const { id, name, grade } = req.body;
students.push({ id, name, grade });
res.status(201).json({ message: 'Student added successfully' });
});

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


const { id } = req.params;
const { name, grade } = req.body;
const studentIndex = students.findIndex(student => student.id === id);
if (studentIndex !== -1) {
students[studentIndex] = { id, name, grade };
res.json({ message: 'Student updated successfully' });
} else {
res.status(404).json({ message: 'Student not found' });
}
});

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


const { id } = req.params;
students = students.filter(student => student.id !== id);
res.json({ message: 'Student deleted successfully' });
});

// Start the server


app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Run your Express.js application:
Start your Express.js server by running the following command in your terminal:
node app.js
Testing the API endpoints with Postman:
Open Postman and send requests to the following endpoints:
GET /students: Retrieve all students.
POST /students: Create a new student. Send a JSON body with id, name, and grade.
PUT /students/:id: Update a student by ID. Send a JSON body with name and grade.
DELETE /students/:id: Delete a student by ID.
That's it! You've created an Express.js web application with REST API endpoints for CRUD
operations on student data using Visual Studio Code. You can further enhance this application by
integrating it with a database like MongoDB to persist the

You might also like