FSWD Final Record
FSWD Final Record
No:
Date:
Ex. No: 01 Design the following static web pages required for an online book store web site.
1.HOME PAGE: The static home page must contain three frames.2.LOGIN
Date: PAGE 3.CATOLOGUE PAGE: The catalogue page should contain the details of
all the books available in the web site in a table. 4. REGISTRATION PAGE.
AIM:
To design the following static web are required for an online book store web site with
home page, login, registration, catalogue pages.
PROCEDURE:
Step-2: The static home page must contain three frames.Top frame, Left frame, Right
frame.
Step-3: The login page contains the user name and the password of the user to
authenticate.
Step-4: The catalogue page should contain the details of all the books available in the
web site in a table.
5
IMPLEMENTATION:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Online Book Store</title>
</head>
<frameset rows="15%,10%,*">
<frameset cols="20%,*">
<frame name="f11" src="logo.html" scrolling="no"></frame>
<frame name="f12" src="title.html" scrolling="no"></frame>
</frameset>
<frameset cols="20%,20%,20%,20%,*">
<frame name="f21" src="home.html"></frame>
<frame name="f22" src="login.html"></frame>
<frame name="f23" src="reg.html"></frame>
<frame name="f24" src="cat.html"></frame>
<frame name="f25" src="cart.html"></frame>
</frameset>
<frameset cols="20%,*">
<frame name="f31" src="branches.html"></frame>
<frame name="f32" src="homepage.html"></frame>
</frameset>
</frameset>
</html>
logo.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<center><img src="images/logo.jpg" width="100" height="100" /></center>
</body>
6
</html>
title.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<h1 align="center">Online Book Store</h1>
</body>
</html>
home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<a href="homepage.html" target="f32">Home</a>
</body>
</html>
login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<a href="loginpage.html" target="f32">Login</a>
</body>
</html>
reg.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
7
</head>
<body>
<a href="regpage.html" target="f32">Registration</a>
</body>
</html>
cat.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<a href="catpage.html" target="f32">Catalogue</a>
</body>
</html>
cart.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<a href="cartpage.html" target="f32">Cart</a>
</body>
</html>
branches.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<ul>
<li>Civil</li>
<li>EEE</li>
<li>Mech</li>
<li>ECE</li>
<li>CSE</li>
<li>MBA</li>
8
<li>MCA</li>
</ul>
</body>
</html>
homepage.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<p align="justify">Welcome to Online Book Store.<br>Here you find all types of books, magazines and
national and international journals.</p>
</body>
</html>
loginpage.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<form>
<table align="center" cellspacing="15px">
<tr>
<td><b>Login</b></td>
<td><input type="text" name="uname" /></td>
</tr>
<tr>
<td><b>Password</b></td>
<td><input type="password" name="upwd" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" />
<input type="reset" />
</td>
</tr>
</table>
</form>
</body>
</html>
regpage.html
<!DOCTYPE html>
9
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form>
<h1 align="center"> REGISTRATION </h1>
<table align="center" cellspacing="10">
<tr>
<td>Name::</td>
<td> <input name="uname" type="text"> </td>
</tr>
<tr>
<td>Password::</td>
<td> <input name="pwd" type="password"> </td>
</tr>
<tr>
<td> E-mail ID:: </td>
<td> <input name="email" type="text"> </td>
</tr>
<tr>
<td> Phone Number:: </td>
<td> <input name="phno" type="text" maxlength="10"> </td>
</tr>
<tr>
<td> Gender:: </td>
<td><input name="gender" type="radio" value="Male"> Male
10
<input type="reset" value="Cancel"> </td>
</tr>
</table>
</form>
</body>
</html>
catpage.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form>
<table cellspacing="10">
<tr>
<td><img src="images/html5.jpg" width="100" height="100"></td>
<td> Title : HTML5 and CSS3 <br>
Author : Sasha Vodnik <br> </td>
<td>Rs. 700 /- </td>
<td><input type="image" src="images/addToCart.jpg" width="150" height="70"></td>
</tr>
<tr>
<td><img src="images/php.jpg" width="100" height="100"></td>
<td> Title : PHP and MYSQL <br>
Author : W. Jason Gilmore <br> </td>
<td>Rs. 650 /- </td>
<td><input type="image" src="images/addToCart.jpg" width="150" height="70"></td>
</tr>
<tr>
<td><img src="images/j2ee.jpg" width="100" height="100"></td>
<td> Title : The Complete Reference JAVA 2 <br>
Author : Herbert Schildt <br> </td>
<td>Rs. 850 /- </td>
<td><input type="image" src="images/addToCart.jpg" width="150" height="70"></td>
</tr>
</table>
</form>
</body>
</html>
cartpage.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
11
</head>
<body>
<h1 align="center">Shopping Cart</h1>
<form>
<table align="center" cellpadding="20px">
<tr>
<th>Product</th>
<th>Description</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
</tr>
<tr>
<td><img src="images/html5.jpg" width="100" height="100" /></td>
PaymentGateway.html
<!DOCTYPE html>
12
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Payment Gateway</title>
</head>
<body>
<h1 align="center">Credit Card Payment Gateway</h1>
<hr>
<form>
<table align="center" cellpadding="20px">
<tr>
<td colspan="2" align="center"><h2>Payment Details</h2></td>
</tr>
<tr>
<td colspan="2">
<b>CARD NUMBER</b><br>
<input type="text" placeholder="Valid Card Number" size="52" />
</td>
</tr>
<tr>
<td><b>Expire Date</b><br><input type="text" placeholder="MM/YY" /></td>
13
OUTPUT:
HOME PAGE:
14
LOGIN PAGE:
REGISTRATION FORM:
CATALOGUE:
15
CART:
16
RESULT:
Thus the home page, login page, catalogue page for the online book store are created
successfully and the output is verified.
Ex. No: 02 Write JavaScript to validate the following fields of the Registration page. 1.First
Name (Name should contains alphabets and the length should not be less than 6
Date: characters). 2. Password (Password should not be less than 6 characters length).
3. E-mail id (should not contain any invalid and must follow the standard
pattern [email protected]) 4. Mobile Number (Phone number should contain
10 digits only). 5. Last Name and Address (should not be Empty)
AIM:
To write JavaScript to validate the following fields of the Registration page. 1.First Name
(Name should contains alphabets and the length should not be less than 6 characters). 2.
Password (Password should not be less than 6 characters length). 3. E-mail id (should not contain
any invalid and must follow the standard pattern [email protected]) 4. Mobile Number (Phone
number should contain 10 digits only). 5. Last Name and Address (should not be Empty)
PROCEDURE:
17
PROGRAM:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>REGISTRATION PAGE</h1>
<form name="registrationForm" onsubmit="return validateForm()">
<label for="firstName">First Name:</label><br>
<input type="text" id="firstName" name="firstName"><br>
<label for="address">Address:</label>
<input type="text" id="address" name="address"><br>
18
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>
Index.js:
function validateForm() {
var firstName = document.forms["registrationForm"]["firstName"].value;
var lastName = document.forms["registrationForm"]["lastName"].value;
var address = document.forms["registrationForm"]["address"].value;
var email = document.forms["registrationForm"]["email"].value;
var mobile = document.forms["registrationForm"]["mobile"].value;
var password = document.forms["registrationForm"]["password"].value;
// Validate address
if (address == "") {
alert("Address must be filled out.");
return false;
}
// Validate email
var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
19
if (!emailRegex.test(email)) {
alert("Invalid email address.");
return false;
}
// Validate password
var passwordRegex = /^[a-zA-Z0-9]{6,}$/;
if (!passwordRegex.test(password)) {
alert(
"Password must be at least 6 characters long and contain only alphanumeric characters."
);
return false;
}
Style.css:
form {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 50px;
border-radius: 20px;
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(94, 28, 28, 0.3);
}
h1 {
color: #4caf50;
align-items: center;
justify-content: center;
display: flex;
}
label {
font-weight: bold;
margin-bottom: 10px;
text-transform: uppercase;
}
input[type="text"],
input[type="email"],
20
input[type="tel"],
input[type="password"] {
padding: 10px;
margin-bottom: 20px;
border-radius: 5px;
box-shadow: 0 0 5px rgba(224, 0, 0, 0.1);
}
input[type="submit"] {
background-color: #4caf50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #3e8e41;
}
OUTPUT:
21
RESULT:
Thus the above program has been executed successfully and the output is verified
Ex. No: 03
Date: Write a javascript to create a Employee Enrollment form and validate the
contents of the form
AIM:
To create an Employee Enrollment form and validate the contents using javascript,
PROCEDURE:
Step 4: Next validate the content of the form using JavaScript and execute the form.
22
IMPLEMENTATION:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Registration Form</title>
</head>
<body>
23
<form name="RegForm" method="post">
<div class="container">
<h1>Registration Form</h1>
<p id="error"></p>
<p>
<br>
<option>BBA</option>
<option>BCA</option>
<option>MBA</option>
<option>MCA</option>
</select>
</p>
<div class="But">
</div>
</div>
</form>
<script src="./index.js"></script>
</body>
</html>
index.js:
24
var address = document.getElementsByName("Address")[0];
if(!/\d/.test(lastCharacter)){
});
e.preventDefault();
errorElement.innerText = "";
if (error) {
errorElement.innerText = error;
return;
console.log("Form Submitter!");
});
function validateForm(){
25
if(!address.value || address.value.length < 5){
address.focus();
return error;
if(!email.value || isValidEmail(email.value)){
email.focus();
return error;
if(!passwd.value || passwd.value.length<8){
passwd.focus();
return error;
phoneno.focus();
return error;
return error;
function isValidEmail(email){
return emailRegex.test(email);
style.css:
*{
26
font-family: sans-serif;
box-sizing: border-box;
margin: 0;
padding: 0;
body{
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: #3a5;
#error{
color: red;
font: bold;
padding: 15px;
input{
padding: 5px
h1{
color: black;
text-align: center;
text-transform: uppercase;
padding-bottom: 15px;
p{
27
color: black;
font-weight: bolder;
padding-bottom: 15px;
letter-spacing: 2px;
.container{
position: relative;
background-color: #eaffd6;
border-radius: 10px;
padding: 20px;
.But{
display: flex;
align-items: center;
justify-content: space-around;
padding-top: 10px;
select option{
font-family: sans-serif;
button{
font-size: large;
font-family: sans-serif;
text-transform: uppercase;
background-color: black;
color: white;
border-radius: 5px;
28
letter-spacing: 2px;
cursor: pointer;
OUTPUT:
29
RESULT:
30
Ex. No: 04
Date: Get data using Fetch API from an open-source endpoint and display the contents
in the form of a card.
AIM:
To write a program for to get data using fetch API from an opensource endpoint and
display the content in the form of a card.
PROCEDURE:
31
IMPLEMENTATION:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>fetch</title>
<link rel="stylesheet" type="text/css"
href="C:\Users\WELCOME\OneDrive\Desktop\workshop\ex1\style.css">
</head>
<body>
<div class="results">
<div id="cat_result" class="result">
<p>Random Cat Placeholder</p>
</div>
<div id="dog_result" class="result">
<p>Random Dog Placeholder</p>
</div>
</div>
<div class="buttons">
<button id="cat_btn">Get Cat</button>
<button id="dog_btn">Get Dog</button>
</div>
<script src=" C:\Users\WELCOME\OneDrive\Desktop\workshop\ex1\script.js "></script>
</body>
</html>
@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');
body {
background-image: linear-gradient( 180deg, rgba(247,247,247,1) 23.8%, rgba(252,221,221,1)
92% );
font-family: 'Open Sans', sans-serif;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
height: 100vh;
margin: 0;
}
.results {
display: flex;
align-items: center;
justify-content: center;
}
32
.result {
background-color: #fff;
display: flex;
align-items: center;
justify-content: center;
margin: 10px;
height: 400px;
width: 300px;
}
.result img {
object-fit: cover;
height: 100%;
width: 100%;
}
.buttons {
display: flex;
align-items: center;
justify-content: center;
}
button {
background-color: darksalmon;
border: 0;
border-radius: 4px;
color: #fff;
font-size: 18px;
padding: 10px;
margin: 10px;
width: 300px;
}
button:active {
transform: scale(0.98);
}
button:focus {
outline: none
}
33
fetch('https://random.dog/woof.json')
.then(res => res.json())
.then(data => {
if(data.url.includes('.mp4')) {
getRandomDog();
}
else {
dog_result.innerHTML = `<img src=${data.url} alt="dog" />`;
}
});
}
34
OUTPUT:
RESULT:
35
The Program has been executed successfully and also verified.
Ex. No: 05
Date: Create a web page using basic css tag. Demonstrate inline, internal and external
style sheets using advanced css
AIM:
To design a web page using basic css tag and demonstrate inline, internal and external style
sheets using advanced css.
PROCEDURE:
Step 4: In html file we created navigation bar, search bar, header and footer using html
tags
Step 5: Using class and id we design the web page using advance css
36
IMPLEMENTATION:
index.html
<!DOCTYPE html>
<html>
<head>
<title>
Online Courses
</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<nav class="navbar background">
<ul class="nav-list">
<div class="logo">
<img src="anna-univ-logo.png" width="1px" height="50px">
</div>
<li><a href="#web">Web Technology</a></li>
<li><a href="#program">C Programming</a></li>
<li><a href="#course">Courses</a></li>
</ul>
<div class="rightNav">
<input type="text" name="search" id="search">
<button class="btn btn-sm">Search</button>
</div>
</nav>
<section class="firstsection">
<div class="box-main">
<div class="firstHalf">
<h1 class="text-big" id="web">
Web Technology
</h1>
<br>
<p class="text-small">
HTML stands for HyperText Markup Language. It is used to design
web pages using a markup language. HTML is the combination of Hypertext and Markup language. Hypertext
defines the link between the Markup language. Hypertext defines
37
the link between the web a markup language is used to define the text document within tag which defines the
structure of web pages. HTML is a markup language that is used by the browser to manipulate text, images, and
other content to display it in the requiredformat.
</p>
</div>
</div>
</section>
<section class="secondsection">
<div class="box-main">
<div class="secondHalf">
<h1 class="text-big" id="program">
C Programming
</h1>
<p class="text-small">
C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming
language to write operating system. The main features of C language include low-level access to memory, simple set
of keywords, and clean style, these features make C language suitable for system programming like operating
system or compiler development.
</p>
</div>
</div>
</section>
<section class="section">
<div class="paras">
<h1 class="sectionTag text-big">Java</h1>
<p class="sectionSubTag text-small">
Java has been one of the most popular programming language for many years.
Java is Object Oriented. However it is not considered as pure object oriented as it provides support for primitive data
types (like int, char, etc) The Java codes are first compiled into bytecode (machine independent code). Then the byte
code is run on Java Virtual Machine .
</p>
</div>
<div class="thumbnail">
<img src="img.png" alt="laptop image">
</div>
</section>
<footer class="background">
<p class="text-footer">
Copyright ©-All rights are reserved
</p>
</footer>
</body>
</html>
38
OUTPUT:
39
RESULT:
Ex. No: 06
Design a Web page using Advanced HTML Forms tags, input-date, time,
Date: number, email, HTML header and footer, spell check and address area.
AIM:
To Design a Web page using Advanced HTML Forms tags, input-date, time, number,
email, HTML header and footer, spell check and address area.
PROCEDURE:
40
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>Advanced HTML Form</title>
<style>
/* Add your CSS styles here */
header, footer {
background-color: #f2f2f2;
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<header>
<h1>Advanced HTML Form</h1>
</header>
<form>
<label for="date">Date:</label>
<input type="date" id="date" name="date" required><br>
<label for="time">Time:</label>
<input type="time" id="time" name="time" required><br>
<label for="number">Number:</label>
<input type="number" id="number" name="number" min="1" max="10" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<label for="editable-area">Editable Area:</label>
<textarea id="editable-area" name="editable-area" rows="4" cols="50" contenteditable></textarea><br>
<input type="submit" value="Submit">
</form>
<footer>
<p>© 2023 My Website. All rights reserved.</p>
</footer>
</body>
41
</html>
OUTPUT:
42
RESULT:
Ex. No: 07
AIM:
To develop and demonstrate JavaScript with POP-UP boxes and functions for the given
problems.
PROCEDURE:
Step 4: Obtain a number using prompt and find the factorial of the number
Step 5: Obtain a number using prompt and get the multiplication table for the number
alert.
Step 6: Obtain two numbers using prompt and continue and obtain the sum of two
numbers using alert.
43
PROGRAM:
1. DISPLAY DATE:
<!DOCTYPE html>
<html>
<head>
<title>Display Date</title>
</head>
<body>
<button onclick="displayDate()">Display Date</button>
<input type="text" id="dateInput">
<script>
function displayDate() {
var currentDate = new Date();
var dateInput = document.getElementById("dateInput");
dateInput.value = currentDate.toDateString();
}
</script>
</body>
</html>
2. FACTORIAL :
<!DOCTYPE html>
<html>
<head>
<title>Factorial</title>
</head>
<body>
<button onclick="calculateFactorial()">Calculate Factorial</button>
<script>
function calculateFactorial() {
44
var number = prompt("Enter a number:");
var factorial = 1;
3.MULTIPLICATION TABLE :
<!DOCTYPE html>
<html>
<head>
<title>Multiplication Table</title>
</head>
<body>
<button onclick="generateMultiplicationTable()">Generate Multiplication Table</button>
<script>
function generateMultiplicationTable() {
var number = prompt("Enter a number:");
var table = "";
<!DOCTYPE html>
<html>
<head>
<title>Sum of Numbers</title>
</head>
<body>
<button onclick="calculateSum()">Calculate Sum</button>
<script>
function calculateSum() {
var number = prompt("Enter a number:");
var sum = Number(number);
45
var confirmAdd = confirm("Do you want to add another number?");
while (confirmAdd) {
var nextNumber = prompt("Enter another number:");
sum += Number(nextNumber);
confirmAdd = confirm("Do you want to add another number?");
}
OUTPUT:
1.
2.
3.
46
4)
47
48
RESULT:
Ex. No: 08 Build an online MCQ quiz app. The questions and options should be fetched
based on the chosen topic from a NodeJS server. The questions can be stored in a
Date: JSON file in the backend. Once the user has answered the questions, the
frontend must send the chosen options to the backend and the backend must
identify the right answers and send the score back to the front end. The frontend
must display the score in a separate neatly designed page.
AIM:
To Build an online MCQ quiz app. The questions and options should be fetched based on
the chosen topic from a NodeJS server. The questions can be stored in a JSON file in the
backend. Once the user has answered the questions, the frontend must send the chosen options to
the backend and the backend must identify the right answers and send the score back to the front
end. The frontend must display the score in a separate neatly designed page.
PROCEDURE:
Step 1: Open Visual Studio Code with the selected project directory.
Step 2: Create server.js file and initialize npm project by using “npm init” command.
49
Step 10: run the program as npm run dev
REQUIRED PACKAGES:
Express
nodemon
IMPLEMENTATION:
Package.json:
{
"name": "mcq-quiz",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"nodemon": "^2.0.22"
}
}
Server.js
const express = require('express');
const app = express();
const port = 3000;
50
app.get("/api/topics", (req, res) => {
const topics = Object.keys(questions);
res.status(200).json({topics});
});
return res.status(200).json({
result,
totalScore
});
})
Questions.json
{
"DSA" : {
"questions": [
{
51
"question": "This set of Data Structure Multiple Choice Questions & Answers (MCQs) focuses on “Binary
Trees using Array”.",
"options": ["2", "any number of children", "0 or 1 or 2", "0 or 1"],
"correctAnswer":3
},
{
"question": "What is/are the disadvantages of implementing tree using normal arrays?",
"options": ["difficulty in knowing children nodes of a node", "difficult in finding the parent of a node",
"have to know the maximum number of nodes possible before creation of trees", "difficult to implement"],
"correctAnswer":3
},
{
"question": "What must be the ideal size of array if the height of tree is ‘l’?",
"options": ["2l-1", "l-1", "l", "2l"],
"correctAnswer":1
}
]
},
"Python" : {
"questions": [
{
"question": "This set of Data Structure Multiple Choice Questions & Answers (MCQs) focuses on “Binary
Trees using Array”.",
"options": ["2", "any number of children", "0 or 1 or 2", "0 or 1"],
"correctAnswer":3
},
{
"question": "What is/are the disadvantages of implementing tree using normal arrays?",
"options": ["difficulty in knowing children nodes of a node", "difficult in finding the parent of a node",
"have to know the maximum number of nodes possible before creation of trees", "difficult to implement"],
"correctAnswer":3
},
{
"question": "What must be the ideal size of array if the height of tree is ‘l’?",
"options": ["2l-1", "l-1", "l", "2l"],
"correctAnswer":1
}
]
}
}
Views->index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/styles.css">
<title>MCQ Quiz App</title>
<style>
/* Add your custom styles here */
</style>
</head>
<body>
52
<h1>MCQ Quiz App</h1>
<label for="topic">Choose a topic:</label>
<select id="topic">
<!-- Add more topic options as needed -->
</select>
<button id="start-quiz">Start Quiz</button>
<div id="quiz-container" style="display: none;">
<h2>Questions:</h2>
</div>
<div id="resultContainer">
<h2 id="result"></h2>
</div>
<script src="/js/script.js"></script>
</body>
</html>
Public->css->styles.css
*{
font-family: sans-serif;
}
body {
padding-left: 3rem;
padding-right: 3rem;
background-color: whitesmoke;
}
h1 {
text-align: center;
}
.error {
color: red;
}
.success {
color: green;
}
.card {
background-color: white;
border-radius: 10px;
padding: 2rem;
margin-bottom: 10px;
}
.card-title {
margin-bottom: 10px;
}
#options {
53
margin-top: 10px;
}
#quiz-container {
margin-top: 10px;
}
.btn-primary {
border-radius: 10px;
height: 40px;
width: 100px;
background-color: dodgerblue;
border: none;
color: white;
cursor: pointer;
font-size: medium;
}
.btn-secondary {
border-radius: 10px;
height: 40px;
width: 100px;
background-color: gray;
color: white;
margin-left: 5px;
border: none;
cursor: pointer;
}
Public->js->script.js
54
});
function displayTopics(topics) {
topics.forEach(topic => {
const option = document.createElement("option");
option.innerText = topic;
topicInput.appendChild(option);
});
}
function displayQuestions(questions) {
quizContainer.innerHTML = "";
const b = document.createElement("b");
b.innerText = `${index + 1}. ${question}`;
b.classList.add("card-title");
55
input.type = "radio";
input.id = option;
input.value = option;
input.name = question;
input.addEventListener("change", handleInputChange);
field.id=question;
field.appendChild(input);
field.appendChild(label);
optionsContainer.appendChild(field);
});
questionContainer.appendChild(b);
questionContainer.appendChild(optionsContainer);
quizContainer.appendChild(questionContainer);
});
quizContainer.appendChild(button);
quizContainer.style.display = "block";
}
displayResult(result, totalScore);
} catch (err) {
console.log(err);
}
}
function handleInputChange(e) {
const { name, value } = e.target;
answers[name] = value;
56
console.log(answers);
}
57
OUTPUT:
58
RESULT:
Thus the above program is executed successfully and also verified.
Ex. No: 09
Date: Change a Content of webpage using AJAX. Perform Different Operations using
JQUERY Selectors.
AIM:
PROCEDURE:
59
IMPLEMENTATION:
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
/>
<title>Blog Post</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
<div class="navbar navbar-dark bg-dark p-3 mb-3">
<h1 class="navbar-brand">Blog Posts</h1>
</div>
<div class="container" id="container"></div>
</div>
<script src="./scripts.js"></script>
</body>
</html>
scripts.js
$(document).ready(function () {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
method: "GET",
60
success: function (posts) {
let result = ``;
posts.forEach(function (post, index) {
result += `<div class="card mb-3">
<div class="card-header">
<h1>${index + 1}. ${post.title}</h1>
</div>
<div class="card-body">
<p>${post.body}</p>
</div>
</div>`;
});
$("#container").html(result);
}
});
});
OUTPUT:
61
RESULT:
The program has been executed successfully and output has been obtained.
Ex. No: 10
Date: Create a NodeJS server that serves static HTML and CSS files to the user
without using Express
Aim:
To write a program for create a Nodejs server that server static HTML and CSS file to
the user without using express.
Procedure:
Step 3: Next created HTML page to design in CSS and that age connect with
Nodejs server.
Step 5: Next run the program in your web browser on the local host
62
IMPLEMENTATION:
index.html
<!DOCTYPE html>
<html>
<body>
<h1>This is MCA page</h1>
<h1>TIME TABLE</h1>
<table border="5" cellspacing ="0" align="center">
<!--<caption>Timetable</caption>-->
<tr>
<td align="center" height="50"
width="100"><br>
<b>Day/Period</b></br>
</td>
<td align="center" height="50"
width="100"><br>
<b>I<br>9:30-10:20</b>
</td>
<td align="center" height="50"
width="100"><br>
<b>II<br>10:20-11:10</b>
</td>
<td align="center" height="50"
width="100"><br>
<b>III<br>11:10-12:00</b>
</td>
<td align="center" height="50"
width="100"><br>
<b>12:00-12:40</b>
</td>
<td align="center" height="50"
63
width="100"><br>
<b>IV<br>12:40-01:30</b>
</td>
<td align="center" height="50"
width="100"><br>
<b>V<br>01:30-02:20</b>
</td>
<td align="center" height="50"
width="100"><br>
<b>VI<br>02:20-03:10</b>
</td>
<td align="center" height="50"
width="100"><br>
<b>VII<br>03:10-04:00</b>
</td>
</tr>
<tr>
<td align="center" height="50">
<b>MONDAY</b></td>
<td align="center" height="50">ENG</td>
<td align="center" height="50">MAT</td>
<td align="center" height="50">CHE</td>
<td rowspan="6" align="center" height="50">
<h2>L<br>U<br>N<br>C<br>H</h2>
</td>
<td colspan="3" align="center"
height="50">LAB</td>
<td align="center" height="50">PHY</td>
</tr>
<tr>
<td align="center" height="50">
<b>TUESDAY</b>
</td>
<td colspan="3" align="center"
height="50">LAB
</td>
<td align="center" height="50">ENG</td>
<td align="center" height="50">CHE</td>
<td align="center" height="50">MAT</td>
<td align="center" height="50">SPORTS</td>
</tr>
<tr>
<td align="center" height="50">
<b>WEDNESDAY</b>
</td>
<td align="center" height="50">MAT</td>
<td align="center" height="50">PHY</td>
<td align="center" height="50">ENG</td>
<td align="center" height="50">CHE</td>
<td colspan="3" align="center"
height="50">LIBRARY
</td>
</tr>
64
<tr>
<td align="center" height="50">
<b>Thursday</b>
</td>
<td align="center" height="50">Phy</td>
<td align="center" height="50">Eng</td>
<td align="center" height="50">Che</td>
<td colspan="3" align="center"
height="50">LAB
</td>
<td align="center" height="50">Mat</td>
</tr>
<tr>
<td align="center" height="50">
<b>Friday</b>
</td>
<td colspan="3" align="center"
height="50">LAB
</td>
<td align="center" height="50">Mat</td>
<td align="center" height="50">Che</td>
<td align="center" height="50">Eng</td>
<td align="center" height="50">Phy</td>
</tr>
<tr>
<td align="center" height="50">
<b>Saturday</b>
</td>
<td align="center" height="50">Eng</td>
<td align="center" height="50">Che</td>
<td align="center" height="50">Mat</td>
<td colspan="3" align="center"
height="50">SEMINAR
</td>
<td align="center" height="50">SPORTS</td>
</tr>
</table>
</body>
</html>
Server.js
65
} else if (req.url == "/student") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is student Page.</p></body></html>');
res.end();
} else if (req.url == "/admin") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is admin Page.</p></body></html>');
res.end();
} else
res.end('Invalid Request!');
});
server.listen(4000);
console.log('Node.js web server at port 4000 is running..')
OUTPUT:
66
RESULT:
Ex. No: 11 Create a NodeJS server using Express that stores data from a form as a JSON
file and displays it in another page. The redirect page should be prepared using
Date: Handlebars.
Aim:
To write a program to create a NodeJS server using Express that stores data from a form
as a JSON file and displays it in another page. The redirect page should be prepared
using Handlebars.
Procedure:
67
Implementation:
Installing the following packages:
npm init
npm install express –save
npm install express-handlebars –save
index.js
const express = require('express');
const app = express();
const port = 3000;
const {engine}= require('express-handlebars');
app.set('view engine', 'hbs');
app.engine('hbs', engine({
layoutsDir: __dirname + '/views/layouts',
extname: 'hbs',
defaultLayout: 'planB',
partialsDir: __dirname + '/views/partials/'
}));
app.use(express.static('public'))
fakeApi = () => {
return [
{
name: 'Katarina',
lane: 'midlaner'
},
{
name: 'Jayce',
lane: 'toplaner'
},
{
68
name: 'Heimerdinger',
lane: 'toplaner'
},
{
name: 'Zed',
lane: 'midlaner'
},
{
name: 'Azir',
lane: 'midlaner'
}
];
}
app.get('/', (req, res) => {
res.render('main', {layout: 'index', suggestedChamps: fakeApi(), listExists: true});
});
app.listen(port, () => console.log(`App listening to port ${port}`));
create a folder by the name of “public” in which we create a style.css file
style.css
li {
font-size: 2rem;
width: 300px;
margin: 4px;
padding: 4px;
list-style: none
}
.midlaner {background-color: #ffea00}
.toplaner {background-color: #eeeeee}
main.hbs
{{> lovedChamps}}
{{> hatedChamps}}
<ul>
{{#if listExists}}
{{#each suggestedChamps}}
<li class={{this.lane}}>{{this.name}}</li>
{{/each}}
{{/if}}
</ul>
hatedChamps.hbs
<h2>Lists of my most hated League champions</h2>
<ul>
<li class="midlaner">Yasuo</li>
<li class="midlaner">Zoe</li>
69
<li class="toplaner">Mundo</li>
<li class="toplaner">Darius</li>
<li class="midlaner">Fizz</li>
</ul>
lovedChamps.hbs
<h2>Lists of my most loved League champions</h2>
<ul>
<li class="midlaner">Leblanc</li>
<li class="midlaner">Lux</li>
<li class="toplaner">Teemo</li>
<li class="midlaner">Kassadin</li>
<li class="toplaner">Jarvan IV</li>
</ul
index.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Best Website</title>
<meta name="HandheldFriendly" content="True" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<link rel="stylesheet" type="text/css" href="./style.css" />
</head>
<body>
{{{body}}}
</body>
</html>
planB.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Best Website</title>
<meta name="HandheldFriendly" content="True" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<link rel="stylesheet" type="text/css" href="./style.css" />
</head>
<body>
{{{body}}}
<h1>HAHAHAHAHAHAHH</h1>
</body> </html>
70
OUTPUT:
71
RESULT:
Ex. No: 12 Create a NodeJS server using Express (i) To creates, reads, updates and deletes
student details and stores them in MongoDB database.(ii)The information about
Date: the user should be obtained from a HTML form.
Aim:
To write a program to create a NodeJS server using Express that creates, reads, updates
and delete students details and stores them in MongoDB database. The information should be
obtained from a HTML.
Procedure:
72
Implementation:
index.js
var express = require("express");
var app = express();
var port = 3000;
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var mongoose = require("mongoose");
mongoose.Promise = global.Promise; mongoose.connect("mongodb://127.0.0.1:27017/ex5");
var studentsSchema = new mongoose.Schema({
fname: String,
lname: String,
rollno: Number
});
var User = mongoose.model("User", studentsSchema);
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
73
app.post("/addname", (req, res) => {
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("database saved");
})
.catch(err => {
res.status(400).send("Unable to save to database");
});
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>Student Database</title>
</head>
<body>
<h1>Student Database</h1>
<form method=”post” action=”/addname”>
<label for=”fname”>First name:</label><br><br>
<input type=”text” id=”fname” name=”fname” placeholder=”name”><br><br>
<label for=”lname”>Last name:</label><br><br>
<input type=”text” id=”lname” name=”lname” placeholder=”name”><br><br>
<label for=”rollno”>Roll no:</label><br><br>
<input type=”text” id=”rollno” name=”rollno” placeholder=”rollno”><br><br>
<input type=”submit” value=”submit”>
<input type=”reset”>
</form>
</body>
</html>
74
75
76
OUTPUT:
Up
UPDATE:
77
>use ex5;
>'switched to db ex5'
>db.users.updateOne({'fname':'jayabarani'},{$set:{'lname':'palanivel'}})
Delete
>db.users.remove({‘fname’:’jayabarani’})
78
79
RESULT:
The Program has been executed successfully and also verified
Ex. No: 13
Date: Develop API with Express Framework for online Gas Booking Management
System.
AIM:
To Develop API with Express Framework for online Gas Booking Management System.
PROCEDURE:
Step 1: Open Visual Studio Code with the selected project directory.
Step 2: Create server.js file and initialize npm project by using “npm init” command.
80
Step 6: Create booking.js in models->booking.js
Step 9: Enter the url http://localhost:3000/bookings in thunder client change the get
method to post method and click send.
IMPLEMENTATION:
Package.json:
{
"name": "gas-booking",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.2",
"express": "^4.18.2",
"mongoose": "^7.3.0"
}
}
81
server.js
// Connect to MongoDB
mongoose
.connect("mongodb://localhost/gas_booking", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to MongoDB");
})
.catch((err) => {
console.error("Error connecting to MongoDB:", err);
});
82
newBooking
.save()
.then((booking) => {
res.json(booking);
})
.catch((err) => {
res.status(500).json({ error: "Error creating booking" });
});
};
module.exports = Booking;
83
OUTPUT:
84
RESULT:
Ex. No: 14 Build a blog website where you can add blog posts through a simple admin panel
and the users can view the blog posts. The contents of the blog posts can be
85
Date: stored in either MongoDB. The home page should contain the titles of the blog
post and the full post can be viewed by clicking the title. Frontend can be built
either using React or through template engines served by the NodeJS server.
AIM:
To Build a blog website where you can add blog posts through a simple admin panel and
the users can view the blog posts. The contents of the blog posts can be stored in either
MongoDB. The home page should contain the titles of the blog post and the full post can be
viewed by clicking the title. Frontend can be built either using React or through template engines
served by the NodeJS server.
PROCEDURE:
Step 1: Open the visual studio code with the selected project directory.
Step 2: Create a server.js and initialize the npm project by using “ npm init” command
REQUIRED PACKAGES:
1. express
2. mongoose
3. ejs
86
IMPLEMENTATION:
Package.json:
{
"name": "blog3",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.2",
"mongoose": "^7.3.0"
}
}
server.js
// Connect to MongoDB
mongoose.connect('mongodb://127.0.0.1:27017/blog');
const db = mongoose.connection;
87
const posts = await BlogPost.find({ });
res.render("index", { posts });
} catch (err) {
console.log(err);
}
});
views->index.ejs
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/styles.css">
<title>Blog</title>
</head>
<body>
<div class="container">
<h1>Welcome to the Blog</h1>
<% posts.forEach((post) => { %>
<div class="card">
<h2 class="card-header"><%= post.title %></h2>
<div class="card-body"><%= post.content.slice(0, 100) + "...." %><a href="/post/<%= post._id %>">read
more</a></div>
</div>
<% }); %>
</div>
</body>
</html>
views->post.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= post.title %></title>
</head>
<body>
88
<h1><%= post.title %></h1>
<p><%= post.content %></p>
</body>
</html>
public->css->styles.css
*{
font-family: sans-serif;
box-sizing: border-box;
}
body {
background-color: whitesmoke;
}
h1 {
text-align: center;
}
.container {
padding: 20px;
}
.card {
background-color: white;
border-radius: 5px;
padding: 1rem;
}
.card-header {
margin: 0;
border-bottom: 1px solid gray;
}
.card-body {
padding-top: 10px;
}
89
OUTPUT:
RESULT:
90
Thus the above program is executed successfully and also verified.
Ex. No: 15
Aim:
Procedure:
Step 1: Open Visual Studio Code with the selected project directory.
Step 2: Create server.js file and initialize npm project by using “npm init” command.
Step 6: Set up routes and route handlers for following methods GET, POST, PUT,
DELETE.
Step 7: Start the development server by running “npm run dev” command.
Step 8: Use REST client program like postman to verify the output.
91
IMPLEMENTATION:
Package.json
{
"name": "books-api",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
"dev": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"mongoose": "^7.2.2"
},
"devDependencies": {
"nodemon": "^2.0.22"
}
}
Server.js
app.use(express.json());
92
publication: {
type: String,
required: true
},
price: {
type: String,
required: true
},
publishedOn: {
type: Date,
default: Date.now
}
});
res.status(200).json({
books
});
} catch (err) {
res.status(500).json({
message: "Internal Server error"
});
}
});
app.post("/book", async (req, res) => {
const body = req.body;
const book = new Book(body);
try {
await book.save();
res.status(201).json({
message: `Successfully saved book with the title ${book.title}`
});
} catch (err) {
console.log(err);
res.status(500).json({
message: "Internal Server error"
});
}
});
app
.route("/book/:id")
.put(async (req, res) => {
const { id } = req.params;
93
try {
const book = await Book.findByIdAndUpdate(id, req.body);
return res.status(200).json({
message: "Successfully updated the book!"
});
} catch (err) {
res.status(500).json({
message: "Internal Server error"
});
}
})
.delete(async (req, res) => {
const { id } = req.params;
try {
const bookQuery = await Book.findByIdAndDelete(id);
return res.status(200).json({
message: `Successfully deleted book with title ${bookQuery.title}`
});
} catch (err) {
res.status(500).json({
message: "Internal Server error"
});
}
});
app.listen(3000, () => {
console.log("Server started on port 3000");
connectDB();
});
94
OUTPUT:
95
96
RESULT:
The program has been executed successfully and output has been obtained.
Ex. No: 16 Create a simple Sign up and Login mechanism and authenticate the user using
cookies. The user information can be stored in either MongoDB or MySQL and
Date: the server should be built using NodeJS and Express Framework
AIM:
To write a program to Create a simple Sign up and Login mechanism and authenticate the
user using cookies. The user information can be stored in either MongoDB or MySQL and the
server should be built using NodeJS and Express Framework
PROCEDURE:
97
Step4: create javaScript file named app.js
IMPLEMENTATION:
98
try{
let foundUser = users.find((data) => req.body.email === data.email);
if (!foundUser) {
let hashPassword = await bcrypt.hash(req.body.password, 10);
let newUser = {
id: Date.now(),
username: req.body.username,
email: req.body.email,
password: hashPassword,
};
users.push(newUser);
console.log('User list', users);
res.send("<div align ='center'><h2>Registration successful</h2></div><br><br><div
align='center'><a href='./login.html'>login</a></div><br><br><div align='center'><a
href='./registration.html'>Register another user</a></div>");
} else {
res.send("<div align ='center'><h2>Email already used</h2></div><br><br><div
align='center'><a href='./registration.html'>Register again</a></div>");
}
} catch{
res.send("Internal server error");
}
});
app.post('/login', async (req, res) => {
try{
let foundUser = users.find((data) => req.body.email === data.email);
if (foundUser) {
let submittedPass = req.body.password;
let storedPass = foundUser.password;
const passwordMatch = await bcrypt.compare(submittedPass, storedPass);
if (passwordMatch) {
let usrname = foundUser.username;
res.send(`<div align ='center'><h2>login successful</h2></div><br><br><br><div align
='center'><h3>Hello ${usrname}</h3></div><br><br><div align='center'><a
href='./login.html'>logout</a></div>`);
} else {
res.send("<div align ='center'><h2>Invalid email or password</h2></div><br><br><div align
='center'><a href='./login.html'>login again</a></div>");
}
}
else {
let fakePass = `$2b$$10$ifgfgfgfgfgfgfggfgfgfggggfgfgfga`;
await bcrypt.compare(req.body.password, fakePass);
res.send("<div align ='center'><h2>Invalid email or password</h2></div><br><br><div
align='center'><a href='./login.html'>login again<a><div>");
}
} catch{
res.send("Internal server error");
}
});
server.listen(3000, function(){
console.log("server is listening on port: 3000");
});
99
HTML FILE: login.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title> My Form </title>
<style>
#mylink{
font-size: 25px;
}
</style>
</head>
<body align='center'>
<header>
<h1>Login</h1>
</header>
<form action="/login" method="POST">
<fieldset>
<label>Email ID</label>
<input type ="email" id = 'email' name="email" placeholder="[email protected]" required>
<br><br>
<label>Password</label>
<input type="password" id = "password" name="password" required>
<br><br>
<button type ="reset">Reset</button>
<button type ="submit">Submit</button>
</fieldset>
</form>
<br><br>
<a id="mylink" href="./registration.html">register</a>
</body>
</html>
registration.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title> My Form </title>
<style>
#mylink{
font-size: 25px;
}
</style>
</head>
<body align='center'>
<header>
<h1>Register</h1>
</header>
<form action="/register" method="POST">
100
<fieldset>
<label>Username</label>
<input type ="text" id = 'username' name="username" placeholder="maverick" required>
<br><br>
<label>Email ID</label>
<input type ="email" id = 'email' name="email" placeholder="[email protected]" required>
<br><br>
<label>Password</label>
<input type="password" id = "password" name="password" required>
<br><br>
<button type ="reset">Reset</button>
<button type ="submit">Submit</button>
</fieldset>
</form>
<br><br>
<a id="mylink" href="./login.html">login</a>
</body>
</html>
OUTPUT:
101
102
RESULT:
Thus the above program is executed successfully and also verified.
Ex. No: 17 Build a simple calculator app with React. The user should be able to add
numbers and Operations to the app by clicking on buttons, just like you would
Date: do in a mobile phone. The moment the operation and the two operations are
defined, the answer should be displayed.
AIM:
To Build a simple calculator app with React. The user should be able to add numbers and
Operations to the app by clicking on buttons, just like you would do in a mobile phone. The
moment the operation and the two operations are defined, the answer should be displayed.
PROCEDURE:
103
Step 1: Open Visual Studio Code with the selected project directory.
Step 2: Create server.js file and initialize npm project by using “npm init” command.
REQUIRED PACKAGES:
1. Parcel
2. React
3. React-dom
IMPLEMENTATION:
package.json:
{
"name": "calculator",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "parcel public/index.html"
104
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"parcel": "^2.9.2",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"process": "^0.11.10"
}
}
public->index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.15.4/css/all.css"
integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm"
crossorigin="anonymous"
/>
<title>Calculator</title>
</head>
<body>
<div id="root"></div>
<script src="../src/index.js" type="module"></script>
</body>
</html>
src->App.jsx
105
setCurrentOperand(prev => (prev.length <= 1 ? "0" : prev.slice(0, prev.length - 1)));
}
if (isNumber(value)) {
setCurrentOperand(prev => (prev === "0" ? text : prev + text));
}
if (isOperator(value)) {
if (value !== "^2" && value !== "^3") {
setOperator(text);
setPreviousOperand(`${currentOperand} ${text}`);
setCurrentOperand("0");
}
106
}
return (
<div className="calculator">
<Display sub={previousOperand} main={currentOperand} />
<div className="btn-container">
{BUTTONS.map(button => renderButton(button, handleClick))}
</div>
</div>
);
};
src->index.css:
@import url("https://fonts.googleapis.com/css2?family=Poppins&display=swap");
:root {
--btn-height: 60px;
--btn-width: 80px;
--default-color: gray;
--btn-default-color: #f9f9f9;
--btn-default-hover: #eeeded;
--btn-primary-color: #0067c0;
--btn-primary-hover: rgb(61, 125, 243);
--btn-white-color: #ffffff;
--btn-white-hover: rgb(255, 247, 253);
--calculator-background-color: #f3f3f3;
}
*{
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
107
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background-color: rgb(121, 118, 118);
overflow: hidden;
}
.calculator {
background-color: var(--calculator-background-color);
padding: 8px;
border-radius: 5px;
}
.btn {
border: none;
height: var(--btn-height);
width: var(--btn-width);
padding: 10px;
font-size: 18px;
border-radius: 5px;
cursor: pointer;
transition: 0.2s;
}
.btn-default {
background-color: var(--btn-default-color);
}
.btn-default:hover {
background-color: var(--btn-default-hover);
}
.btn-primary {
background-color: var(--btn-primary-color);
color: white;
transition: 0.2s;
}
.btn-primary:hover {
background-color: var(--btn-primary-hover);
}
.btn-white {
background-color: white;
transition: 0.2s;
}
.btn-white:hover {
background-color: var(--btn-white-hover);
}
108
.btn-container {
display: grid;
align-items: center;
grid-template-columns: repeat(4, var(--btn-width));
gap: 4px;
}
.rotate-45 {
transform: rotate(45deg);
}
.operator {
font-size: 24px;
}
.display {
min-height: 100px;
padding: 10px;
text-align: right;
}
.sub-display {
padding: 5px;
min-height: 35px;
font-size: 16px;
color: var(--default-color);
}
.main-display {
font-size: 45px;
padding: 5px;
min-height: 80px;
}
src->index.js
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
src->script.js
class Calculator {
109
constructor(prevOperandTextElement, currentOperandTextElement) {
this.prevOperandTextElement = prevOperandTextElement;
this.currentOperandTextElement = currentOperandTextElement;
this.clear();
}
clear() {
this.previousOperand = "";
this.currentOperand = "0";
this.operation = undefined;
}
chooseOperation(operation) {
if (this.currentOperand === "0") return;
this.operation = operation;
this.previousOperand = this.currentOperand;
this.currentOperand = "0";
}
clearCurrentOperand() {
this.currentOperand = "0";
}
delete() {
if (this.currentOperand.length === 1) {
this.currentOperand = "0";
} else {
this.currentOperand = this.currentOperand.slice(0, -1);
}
}
compute() {
let result = 0;
let previousOperand = parseFloat(this.previousOperand);
let currentOperand = parseFloat(this.currentOperand);
switch (this.operation) {
case "+":
result = previousOperand + currentOperand;
break;
case "-":
result = previousOperand - currentOperand;
break;
case "*":
result = previousOperand * currentOperand;
break;
110
case "/":
result = previousOperand / currentOperand;
break;
case "^2":
result = Math.pow(currentOperand, 2);
break;
case "^3":
result = Math.pow(currentOperand, 3);
break;
default:
result = 0;
}
this.currentOperand = result;
this.operation = undefined;
this.previousOperand = "";
}
apppendNumber(number) {
if (number === "." && this.currentOperand.includes(".")) return;
if (this.currentOperand.length === 8) return;
getOperationSymobol() {
const operation = this.operation;
return operation;
}
updateDisplay() {
this.currentOperandTextElement.innerText = this.currentOperand;
111
this.prevOperandTextElement.innerText = `${this.previousOperand} ${this.getOperationSymobol()}`;
}
}
numberButtons.forEach(numberButton => {
numberButton.addEventListener("click", e => {
const number = e.target.innerText;
calculator.apppendNumber(number);
calculator.updateDisplay();
});
});
operatorButtons.forEach(operatorButton => {
operatorButton.addEventListener("click", e => {
const operator = e.target.value;
calculator.chooseOperation(operator);
calculator.updateDisplay();
});
});
clearAllButton.addEventListener("click", () => {
calculator.clear();
calculator.updateDisplay();
});
clearCurrentOperandButton.addEventListener("click", () => {
calculator.clearCurrentOperand();
calculator.updateDisplay();
});
deleteButton.addEventListener("click", () => {
calculator.delete();
calculator.updateDisplay();
});
src->components->Button.jsx:
112
const Button = ({ value, color = "default", children, onClick }) => {
return (
<button
className={`btn btn-${color}`}
onClick={e => onClick({ value: e.target.value, text: e.target.innerText })}
value={value ? value : ""}
>
{children}
</button>
);
};
src->Components->Display.jsx
src->Constants->index.js:
"1/x",
"^2",
"^3",
"/",
"7",
"8",
"9",
"*",
"4",
"5",
"6",
"-",
113
"1",
"2",
"3",
"+",
"+/-",
"0",
".",
"="
];
src->utils->index.js:
src->utils->renderButton.js:
114
</Button>
);
if (button === "*")
return (
<Button key={button} onClick={handleClick} value={button}>
×
</Button>
);
if (button === "delete")
return (
<Button key={button} onClick={handleClick} value={button}>
<i className="fas fa-backspace"></i>
</Button>
);
if (button.length <= 1 && button.charCodeAt(0) >= 48 && button.charCodeAt(0) <= 57) {
return (
<Button key={button} onClick={handleClick} color="white" value={button}>
{button}
</Button>
);
}
OUTPUT:
115
RESULT:
Thus the above program is executed successfully and also verified.
116
Ex. No: 18 Create a NodeJS server that creates, reads, updates and deletes event
details and stores them in a MySQL database. The information about the user
Date: should be obtained from a HTML form
AIM:
To write a program to create a NodeJS server that creates, reads, updates and deletes
event details and store them in a MySQL database. The information about the user should be
obtained from a HTML form.
PROCEDURE:
Step4: And the body parser and nodemon install to the following commands
npm install body parser –save
npm install nodemon –save
117
IMPLEMENTATION:
mysqlConnection.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
app.listen(8080, function(){
console.log(`Listening on port 8080..`)
});
app.get('/students' , (req, res) => {
mysqlConnection.query('SELECT * FROM students', (err, rows, fields) => {
if (!err)
res.send(rows);
else
console.log(err);
});
} );
118
//Router to INSERT/POST a Student's detail
else
console.log(err);
})
});
119
OUTPUT:
MYSQL Workbench
120
Create database db_college;
121
);
use db_college;
select * from students;
122
Open up a browser and navigate to the url: http://localhost:8080/students
Postman
123
GET students
POST – Create
POST – Update
124
DELETE
125
RESULT:
AIM:
PROCEDURE:
Step 1: Open visual studio code with the selected project directory.
Step 3: Create app.js file and initialize npm project by using “npm init” command.
126
Step 7: Enter the url http://localhost:3000/ in browser.
IMPLEMENTATION:
package.json
{
"name": "mongo2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"mongodb": "^5.6.0"
}
}
index.html
<!DOCTYPE html>
<html>
127
<head>
<title>Add User</title>
</head>
<body>
<h1>Add User</h1>
<form action="/users" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
app.js
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'mydatabase';
128
// Use connect method to connect to the server
client.connect((err) => {
assert.strictEqual(null, err);
console.log('Connected successfully to server');
const db = client.db(dbName);
client.close();
});
});
OUTPUT:
129
RESULT:
Thus the above program is executed successfully and also verified.
Ex. No: 20 Create a Todo application using ReactJS. Store the data to a JSON file using a
simple NodeJS server and retrieve the information from the same during page
Date: reloads
Aim:
To write a program to create a Todo application using ReactJS store the data to a JSON
file using a simple NodeJS server and retrieve the information from the same during
page reloads.
Procedure:
130
Step5: Stop the program
IMPLEMENTATION:
function App() {
return (
<div className='container border border-primary rounded mt-5' >
<Todo/>
</div>
);
}
export default App;
index.js
131
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.css'
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
App.css
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
132
to {
transform: rotate(360deg);
}
}
.container {
background-color:lightseagreen;
}
const handleClear=()=>{
setTasks([]);
localStorage.removeItem("localTasks");
}
return (
<div className="container row">
<h1 className="mt-3 text-white">To-Do App</h1>
<div className="col-8">
<input
name="task"
type="text"
value={task}
placeholder="Write your task..."
133
className="form-control"
onChange={(e) => setTask(e.target.value)}
/>
</div>
<div className="col-4">
<button
className="btn btn-primary form-control material-icons"
onClick={addTask}
>
add
</button>
</div> <div className="badge">b
You have
{!tasks.length
? " no tasks"
: tasks.length === 1
? " 1 task"
: tasks.length > 1
? ` ${tasks.length} tasks`
: null}
</div>
{tasks.map((task) => (
<React.Fragment key={task.id}>
<div className="col-11">
<span className = "form-control bg-white btn mt-2"
style={{textAlign: "left", fontWeight: "bold"}}>
{task.title}
</span>
</div>
<div className="col-1">
<button
className =" mt-2 btn btn-warning material-icons"
onClick ={()=> handleDelete(task)}
>delete</button>
</div>
</React.Fragment>
))}
{!tasks.length ? null:(
<div>
<button className= "btn btn-secondary mt-4 mb-4" onClick={()=>handleClear()}>
Clear
</button>
</div>
)}
</div>
);
}
134
OUTPUT:
135
RESULT:
Ex. No: 21
AIM:
PROCEDURE:
136
cd counter
IMPLEMENTATION:
137
setCounter(counter - 1)
}
return (
<div style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
fontSize: '300%',
position: 'absolute',
width: '100%',
height: '100%',
top: '-15%',
}}>
Counter App
<div style={{
fontSize: '120%',
position: 'relative',
top: '10vh',
}}>
{counter}
</div>
<div className="buttons">
<button style={{
fontSize: '60%',
position: 'relative',
top: '20vh',
marginRight: '5px',
backgroundColor: 'green',
borderRadius: '8%',
color: 'white',
}}
onClick={handleClick1}>Increment</button>
<button style={{
fontSize: '60%',
position: 'relative',
top: '20vh',
marginLeft: '5px',
backgroundColor: 'red',
borderRadius: '8%',
color: 'white',
}}
onClick={handleClick2}>Decrement</button>
</div>
</div>
)
}
export default App
138
OUTPUT:
139
RESULT:
Thus the above program is executed successfully and also verified.
140
Ex. No: 22
Date: Create and deploy a virtual machine using a virtual box that can be accessed
from the host computer using SSH
Aim:
To write a program to Create and deploy a virtual machine using a virtual box that can
be accessed from the host computer using SSH.
Procedure:
Step4: Then open terminal the using port and call SSH
COMMANDS:
141
OUTPUT:
142
143
RESULT:
Thus the above program is executed successfully and also verified.
144
Ex. No: 23
Date: Create a docker container that will deploy a NodeJS ping server using the
NodeJS image
Aim:
To write a program to Create a docker container that will deploy a NodeJS ping server
using the NodeJS image.
Procedure:
Step 7: Create routes and route handler for HTTP method GET and POST
Step 8: Send html file as response for root route (i.e) “/”, Which has a form that will
make a POST request to the “/” route.
Step 10: After successful build create a container using that image.
Step 12: Now the development server will started and the website can be viewed at
http://localhost:3000/.
145
Required Packages and Tools:
1) Docker Desktop
2) express (npm install express)
Source Code:
File: package.json
{
"name": "ping-server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"ping": "^0.4.4"
}
}
File: Dockerfile
FROM node:alpine
WORKDIR /app
COPY ./ ./
RUN npm install
CMD ["npm", "start"]
File: Server.js
const express = require("express");
const path = require("path");
146
app.post("/", async (req, res) => {
const { name, age } = req.body;
res.send(`
<div>
<h1>Thank you for submitting the details</h1>
<strong>Name: </strong><span>${name}</span>
<br />
<strong>Age: </strong><span>${age}</span>
</div>
`);
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
File:views/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Running Nodejs from Docker Image</title>
</head>
<body>
<form action="/" method="POST">
<h4>Please enter the details</h4>
<div>
<label for="name-input">Enter your name: </label>
<input type="text" name="name" />
</div>
<div>
<label for="age-input">Enter your age: </label>
<input type="number" name="age" />
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
147
To run container from docker image:
OUTPUT:
148
149
RESULT:
Ex. No: 24
AIM:
To deploy a simple guestbook application using docker.
PROCEDURE:
Step 7: Create routes and route handler for HTTP method GET and POST
Step 8: Send html file as response for root route (i.e) “/”, Which has a form that will
make a POST request to the “/” route.
150
Step 9: Build image using “docker build -t ping-server:latest” command
Step 10: After successful build create a container using that image.
Step 12: Now the development server will started and the website can be viewed at
http://localhost:3000/.
REQUIRED PACKAGES:
1. Express
2. Express-handlebars
3. Mongoose
4. Nodemon
IMPLEMENTATION:
package.json
{
"name": "guest-book",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"express-handlebars": "^7.0.7",
"mongoose": "^7.3.0"
},
"devDependencies": {
"nodemon": "^2.0.22"
}
}
server.js
151
const mongoose = require("mongoose");
const { engine } = require("express-handlebars");
res.render("main", {
reviews
});
} catch (err) {
console.log(err.message);
}
});
app
.route("/add-review")
.get((req, res) => {
res.render("add");
})
.post(async (req, res) => {
const newReview = new Review(req.body);
try {
await newReview.save();
res.redirect("/");
} catch (err) {
console.log(err);
}
});
152
app.listen(3000, () => {
console.log("Server started on port 3000");
connectDB();
});
models->Review.js
views->add.hbs
<div class="card">
<div class="card-body">
<h2 class="text-center mb-3">Share what you feel with us.</h2>
<form method="POST" action="/add-review">
<div class="form-group mb-1">
<label for="">Name</label>
<input type="text" name="name" class="form-control" placeholder="Your Name" />
</div>
<div class="form-group mb-1">
<label for="">Email</label>
<input
type="email"
name="email"
class="form-control"
placeholder="Your email will be safe with us"
/>
</div>
<div class="form-group">
<label for="">Review</label>
<textarea
153
class="form-control"
rows="4"
placeholder="Write what you feel"
name="body"
></textarea>
</div>
<div class="mt-3 float-end">
<a href="/" class="btn btn-secondary">Cancel</a>
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
</div>
</div>
views->main.hbs
<div class="row">
{{#if reviews}}
{{#each reviews}}
<div class="col-lg-6 col-md-12 mb-2">
<div class="card">
<div class="card-body">{{this.body}}</div>
<div class="card-footer">By: {{this.name}}</div>
</div>
</div>
{{/each}}
{{else}}
<div class="col-lg-12 col-md-12">
<h2 class="text-secondary text-center">No reviews added yet.</h2>
</div>
{{/if}}
</div>
views->layouts->index.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM"
crossorigin="anonymous">
<title>Guestbook</title>
</head>
<body>
{{> header}}
<div class="container mt-3">
{{{body}}}
</div>
</body>
</html>
154
views->partials->header.hbs
OUTPUT:
155
RESULT:
Thus the above program is executed successfully and also verified.
156