0% found this document useful (0 votes)
6 views81 pages

Meanstacklabmanual 11

The document certifies that Bonagiri Meenakshi, a B.Tech III year II semester student, completed 12 experiments in the Mean Stack Technologies laboratory during the academic year 2022-2023. It includes an index of experiments conducted, covering topics such as HTML5, JavaScript, Node.js, Express.js, and TypeScript, along with source code examples for web applications. The document serves as a practical record of the student's work and learning in web development technologies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views81 pages

Meanstacklabmanual 11

The document certifies that Bonagiri Meenakshi, a B.Tech III year II semester student, completed 12 experiments in the Mean Stack Technologies laboratory during the academic year 2022-2023. It includes an index of experiments conducted, covering topics such as HTML5, JavaScript, Node.js, Express.js, and TypeScript, along with source code examples for web applications. The document serves as a practical record of the student's work and learning in web development technologies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

SITAM

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


ACCREDITED BY NAAC, APPROVED BY ACITE, NEW DELHI,
(PERMANENTLY AFFILIATED TO JNTUK, RECOGNISED BY SBTET, GOVERNMENT OF A.P.)

CERTIFICATE
This is to certify that this is a bonafide record of practical work done by

Mr./Ms. BONAGIRI MEENAKSHI

bearing Regd.No 20B61A4511 of B.Tech III year II sem

in Mean Stack Technologies laboratory ofthe

Department of Computer Science And Engineering (AI&DS) Engineering

During the academic year 2022-2023

No.of Experiments done and certified 12

Signature of Lab-in-charge Signature of H.O.D

Signature of Examiners

1) Internal examiner

2) External examiner
INDEX

S. No Date Experiment Page No Remarks

1. 25/01/2023 Introduction to MEAN Stack Technologies.


1. Develop “IEKart’s” website using HTML-5.
2. Enhance the details page of IEKart's Shopping
application by adding a table element to display the 1 - 15
available mobile/any inventories.
3. Types of Statements, Non - Conditional
Statements, Types of Conditional Statements,
if Statements, switch Statements.
2. 01/02/2023 4.Types of Functions, Declaring and Invoking
Function, Arrow Function, Function Parameters, 16 -20
Nested Function, Built-in Functions, Variable Scope
in Functions.
3. 08/02/2023 5. Creating Arrays, Destructuring Arrays, Accessing
Arrays, and Array Methods. 21-29

4. 15/02/2023 6. How to use Node.js


a) Create a web server in Node.js 30-32

5. 22/02/2023 6.c) Modular programming in Node.js 32-34


d) Restarting Node Application&: File Operations
6. 01/03/2023 7.a) Defining a route, Handling Routes, Route
Parameters, Query Parameter 35-40
b) How Middleware works, Chaining of Middlewares,
Types of Middlewares
7. 15/03/2023 7.c) Express.js
d) Models 41-43
8. 29/03/2023 8.a) CRUD Operations
b)API Development 44-48
9. 05/04/2023 8. Write a program to explain session management 49-51
using sessions.
10. 12/04/2023 9. Basics of TypeScript, Functions 52-55
11. 19/04/2023 9. Optional and Default Parameters 56-67
12. 26/04/2023 10. Rest Parameter, Duck Typing 68-70
03/04/2023 11. Extending Interfaces&:Constructor
13. 12. Properties and Methods, What is Generics, What 71-79
are Type Parameters, Generic Functions, Generic
Constraints
20B61A4511 Dept.of Computer Science & Engineering

INTRODUCTION TO MEAN STACK TECHNOLOGIES


➢ MEAN stack is a collection of open-source technologies used to develop web
applications. MEAN stands for MongoDB, Express.js, Angular, and Node.js. In this
explanation, we will focus on the first module of MEAN stack technologies, which
includes HTML5, JavaScript, Node.js, Express.js, and TypeScript.

1|Page

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

1. HTML5: HTML stands for HyperText Markup Language, and HTML5 is the latest
version of this markup language. HTML5 includes new features and elements that
make creating and structuring web pages easier. Some of the new elements in HTML5
are sections, articles, headers, footer, nav, and video. HTML5 also includes support for
multimedia, geolocation, and canvas.
2. JavaScript: JavaScript is a programming language used to create interactive web
applications. JavaScript can be used for both front-end and back-end development. It
is the most popular programming language for web development. JavaScript can be
used to create dynamic effects on web pages, validate forms, and communicate with
web servers.
3. Node.js: Node.js is a server-side JavaScript runtime environment that allows
developers to build scalable, high-performance web applications. Node.js uses an
event-driven, non-blocking I/O model that makes it efficient and lightweight. Node.js
is used to build server-side applications, such as web servers, APIs, and real-time
applications.
4. Express.js: Express.js is a web application framework for Node.js. Express.js provides
a set of features for building web applications, such as routing, middleware, and
templating. Express.js makes it easy to build APIs and web servers quickly and
efficiently. It also provides support for security, file uploads, and cookies.
5. TypeScript: TypeScript is a superset of JavaScript that adds optional static typing and
other features to the language. TypeScript makes it easier to write and maintain
large-scale applications. TypeScript provides features such as interfaces, classes, and
modules that make code more organized and easier to read. It also supports features
such as decorators, which can be used for aspects such as logging or authorization.

2|Page

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Exercise-1
1. AIM: To Create a Web Application for IEKART online shopping website by using
HTML-5

SOURCE CODE:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="IEKart's is an online shopping website that sells
goods in retail. This company deals with various categories like Electronics, Clothing,
Accessories etc.">
<title>IEKart's Shopping Application</title>
<style>
body {
background-color: seagreen;
}
</style>
</head>
<body>
<header>
<h1>IEKart's Shopping Application</h1>
<nav>
<ul>
<li><a href="#electronics">Electronics</a></li>
<li><a href="#clothing">Clothing</a></li>
<li><a href="#accessories">Accessories</a></li>
<li><a href="Login.html">Login</a></li>
<li><a href="SignUp.html">SignUp</a></li>
<li><a href="Track.html">Track Order</a></li>
</ul>
</nav>
</header>

<main>

3|Page

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

<section>
<h2>About Us</h2>
<p>IEKart's is an online shopping website that sells goods in retail. This company
deals with various categories like Electronics, Clothing, Accessories etc.</p>
</section>

<section id="electronics">
<h2>Electronics</h2>
<ul>
<li>Smartphones</li>
<li>Laptops</li>
<li>Tablets</li>
</ul>
</section>

<section id="clothing">
<h2>Clothing</h2>
<ul>
<li>Men's Clothing</li>
<li>Women's Clothing</li>
<li>Kids Clothing</li>
</ul>
</section>

<section id="accessories">
<h2>Accessories</h2>
<ul>
<li>Watches</li>
<li>Jewelry</li>
<li>Bags</li>
</ul>
</section>
</main>

<footer>
<p>&copy; IEKart's Shopping Application</p>
</footer><form>
4|Page

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

<label for="username">Username:</label>
<input type="text" id="username" name="username" contenteditable="true"
spellcheck="true">
<label for="password">Password:</label>
<input type="password" id="password" name="password" contenteditable="true"
spellcheck="true">
<input type="submit" value="Submit">
</form>

</body>
</html>
OUTPUT:

5|Page

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Exercise-2
2. AIM:To Enhance the details page of IEKart's Shopping application.

Source code:
<!DOCTYPE html>
<html>
<head>
<title>IEKart Shopping Application</title>
</head>
<body>
<!-- Navigation Menu -->
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#details">Details</a></li>
<li><a href="#signup">Signup</a></li>
</ul>
</nav>

<!-- Home Page Content -->


<section id="home">
<h1>Welcome to IEKart Shopping Application</h1>
<p>Check out our latest products:</p>
<iframesrc="https://www.youtube.com/embed/dQw4w9WgXcQ"></iframe>
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
6|Page

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

</audio>
<video controls>
<source src="video.mp4" type="video/mp4">
</video>
</section>

<!-- Details Page Content -->


<section id="details">
<h2>Available Mobile Inventories</h2>
<table border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<th>Mobile</th>
<th>Inventories</th>
</tr>
</thead>
<tbody>
<tr>
<td>iPhone</td>
<td rowspan="2">10</td>
</tr>
<tr>
<td>Samsung</td>
</tr>
<tr>
<td>Google Pixel</td>
7|Page

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

<td>5</td>
</tr>
</tbody>
</table>
</section>

<!-- Signup Page Content -->


<section id="signup">
<h2>Signup for IEKart Shopping Application</h2>
<form>
<label for="fullname">Full Name:</label>
<input type="text" id="fullname" name="fullname" 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" minlength="8" required>

<label for="birthdate">Birthdate:</label>
<input type="date" id="birthdate" name="birthdate" required>

<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
8|Page

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

<option value="other">Other</option>
</select>
<label for="interests">Interests:</label>
<datalist id="interests">
<option value="Technology">
<option value="Fashion">
<option value="Sports">
<option value="Food">
</datalist>
<input type="text" id="interests" name="interests" list="interests">

<label for="subscribe">Subscribe to our newsletter:</label>


<input type="checkbox" id="subscribe" name="subscribe">

<input type="submit" value="Signup">


</form>
</section>
</body>
</html>

9|Page

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Output:

10 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Exercise-3
3.AIM: To Calculate the area of the circle using Javascript.
Source code:
<!DOCTYPE html>
<html>
<head>
<title>Area of Circle</title>
<style>
body {
background-color: blue;
color: white;
font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Find the Area of a Circle</h1>
<label for="radius">Enter the radius:</label>
<input type="number" id="radius">
<button onclick="calculateArea()">Calculate</button>
<br><br>
<div id="result"></div>

<script>
function calculateArea() {
// Get the value of the radius input field
11 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

let radius = document.getElementById("radius").value;

// Calculate the area of the circle using the formula


let PI = 3.14159;
let area = PI * radius * radius;

// Display the result in the result div element


document.getElementById("result").innerHTML = "The area of the circle
is: " + area;
}
</script>
</body>
</html>

12 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Output:

13 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

3b. AIM: Write JavaScript code to display the movie details such as movie name, starring,
language, and ratings.
Source Code:
<!DOCTYPE html>
<html>
<head>
<title>Movie Ticket Booking Form</title>
<style>
body {
background-color: pink;
}
</style>
</head>
<body>
<h2>Movie Details</h2>
<p>Movie Name: <span id="movieName">Major</span></p>
<p>Starring: <span id="starring">Adivi Sesh, Sobhita Dhulipala, Saiee
Manjrekar</span></p>
<p>Language: <span id="language">Telugu</span></p>
<p>Ratings: <span id="ratings">8.5/10</span></p>

<h2>Book Tickets</h2>
<form>
<label for="numTickets">Number of Tickets:</label>
<input type="number" id="numTickets" name="numTickets" min="1"
max="10"><br><br>

14 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

<button type="button" onclick="calculatePrice()">Calculate Total


Price</button><br><br>

<label for="totalPrice">Total Price:</label>


<input type="text" id="totalPrice" name="totalPrice" readonly><br><br>

<button type="submit">Book Now</button>


</form>

<script>
constticketPrice = 150;
constfestiveDiscount = 0.1;
constmovieName = "Major";

function calculatePrice() {
let numTickets = document.getElementById("numTickets").value;
let totalPrice = 0;

if (numTickets<= 2) {
totalPrice = numTickets * ticketPrice;
} else if (numTickets>= 6) {
alert("Booking not allowed for more than 5 tickets.");
} else {
totalPrice = numTickets * ticketPrice * (1 - festiveDiscount);
}

15 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

document.getElementById("totalPrice").value = "Rs. " + totalPrice;


}

document.getElementById("movieName").textContent = movieName;
</script>
</body>
</html>
Output:

16 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Exercise-4
4.AIM: To implement an Employee class extending from a base class Person.
Source code:
<!DOCTYPE html>
<html>
<head>
<title>Employee Example</title>
</head>
<body>
<script>
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}

class Employee extends Person {


constructor(name, age, role) {
super(name, age);
this.role = role;
}
}

const employee = new Employee('John Doe', 30, 'Manager');


document.write(`Name: ${employee.name}<br>`);
17 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

document.write(`Age: ${employee.age}<br>`);
document.write(`Role: ${employee.role}`);
</script>
</body>
</html>
Output:

18 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

4d.AIM: To implement object Cloning & Dom object model.


Source code:
<!DOCTYPE html>
<html>
<head>
<title>Ice Cream</title>
<style>
body {
background-color: #F4A460; /* set background color to sandy brown */
}
h1, h2 {
color: #FFFFFF; /* set font color to white */
}
</style>
</head>
<body>
<h1>Ice Cream</h1>

<p>Click the link to see an empty cone:</p>

<a href="#" onclick="changeCone()">Click here</a>

<script>
function changeCone() {
// get the cone image element
const cone = document.getElementById("cone-img");

// get the message and heading elements


const message = document.getElementById("message");
const heading = document.getElementById("heading");

// check if the cone is currently filled


if (cone.src.endsWith("cone-filled.png")) {
// change the image to an empty cone
cone.src = "https://atlas-content-cdn.pixelsquid.com/stock-images/empty-ice-
cream-cone-5EXXW80-600.jpg";
19 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

// update the heading and message


heading.textContent = "Empty Cone";
message.textContent = "Sorry, your ice cream has melted!";

// change the background color


document.body.style.backgroundColor = "#87CEEB"; // set background color
to sky blue
} else {
// change the image to a filled cone
cone.src = "https://encrypted-
tbn0.gstatic.com/images?q=tbn:ANd9GcSuG4fPacWfz2dsnm7TfYsKeS-
qfF7EY2T2aA&usqp=CAU";

// update the heading and message


heading.textContent = "Ice Cream Cone";
message.textContent = "Enjoy your delicious ice cream!";

// change the background color


document.body.style.backgroundColor = "#F4A460"; // set background color
to sandy brown
}
}
</script>

<!-- cone image element -->


<img id="cone-img" src="cone-filled.png" alt="Ice Cream Cone">

<!-- heading and message elements -->


<h2 id="heading">Ice Cream Cone</h2>
<p id="message">Enjoy your delicious ice cream!</p>
</body>
</html>

20 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Output:

21 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Exercise-5
5a.AIM:To Create an array of objects having movie details.

Source code:
<!DOCTYPE html>
<html>
<head>
<title>Movie Details</title>
<style>
body {
background-color: #F4A460; /* set background color to sandy brown */
}

</style>

</head>
<body>
<div id="movies"></div>

<script>
// Create an array of movie objects
const movies = [
{
name: "Major",
starring: "Adivi Sesh, Sobhita Dhulipala",
language: "Telugu",
ratings: "7.8/10"
},
{
name: "Gudachari",
starring: "Adivi Sesh, Sobhita Dhulipala",
language: "Telugu",
ratings: "7.8/10"
},
{
name: "Avaru",
starring: "Siddharth, Aditi Rao Hydari",
language: "Telugu",
ratings: "8.0/10"
}
];

22 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

// Get the movies container element


constmoviesContainer = document.getElementById("movies");

// Loop through the movies array and render the details on the page
movies.forEach((movie) => {
constmovieElement = document.createElement("div");

constnameElement = document.createElement("h2");
nameElement.textContent = movie.name;

conststarringElement = document.createElement("p");
starringElement.textContent = `Starring: ${movie.starring}`;

constlanguageElement = document.createElement("p");
languageElement.textContent = `Language: ${movie.language}`;

constratingsElement = document.createElement("p");
ratingsElement.textContent = `Ratings: ${movie.ratings}`;

movieElement.appendChild(nameElement);
movieElement.appendChild(starringElement);
movieElement.appendChild(languageElement);
movieElement.appendChild(ratingsElement);

moviesContainer.appendChild(movieElement);
});
</script>
</body>
</html>

23 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Output:

24 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

5b. AIM:Simulation of a periodic stock price change and display it on the console

Source code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Stock Price Update</title>

<style>
body {
font-family: Arial, sans-serif;
background-color: #09693c;
}
h1 {
text-align: center;
margin-top: 50px;
}
p{
text-align: center;
font-size: 24px;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Stock Price Update</h1>
<p id="stock-price"></p>

<script>
function getStockPrice() {
return Math.floor(Math.random() * 1000); // returns a random number between
0 and 999
}

// update stock price every three seconds


constintervalId = setInterval(() => {
25 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

conststockPrice = getStockPrice();
conststockPriceElement = document.getElementById('stock-price');
stockPriceElement.textContent = `Current stock price: $${stockPrice}`;
}, 3000);

// stop updating stock price after 1 minute


setTimeout(() => {
clearInterval(intervalId);
conststockPriceElement = document.getElementById('stock-price');
stockPriceElement.textContent = 'Stock price updates stopped.';
}, 60000);
</script>
</body>
</html>

Output:

26 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

27 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

5c. AIM:Simulation of a periodic stock price change and display it on the console.

Source code:

<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #e4a6d3;
}
</style>
</head>
<body>
<h1>Login Form</h1>
<form id="login-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<button type="submit">Login</button>
</form>
<div id="login-result"></div>

<script>
class User {
constructor(username, password) {
this.username = username;
this.password = password;
}

validate(username, password) {
if (this.username === username &&this.password === password) {
return "Login Successful";
} else {
28 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

return "Invalid Credentials";


}
}
}

const user = new User("meenu", "lovely"); // Replace with your desired


credentials

const form = document.getElementById("login-form");


constresultDiv = document.getElementById("login-result");

form.addEventListener("submit", (event) => {


event.preventDefault();
const username = event.target.username.value;
const password = event.target.password.value;
const result = user.validate(username, password);
resultDiv.innerText = result;
form.reset();
});
</script>
</body>
</html>

29 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Output:

30 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Exercise-6
6.AIM:Verify how to execute different functions successfully in the Node.js platform.

Source code:

//Checking the version of node.js

//creating a web server


const http = require('http');

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


res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!');
}).listen(8080);

console.log('Server running at http://localhost:8080/');

31 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Output:

Output:

// app.js

32 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

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

console.log(greeting('John'));

// greeting.js
module.exports = function(name) {
return `Hello, ${name}!`;
};
Output:

33 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

34 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

//workflow of restarting a Node application


const fs = require('fs');
// Read the contents of the file
let contents = fs.readFileSync('src.txt', 'utf8');

// Print the contents of the file


console.log(contents);

// Periodically print the contents of the file to the console


setInterval(() => {
console.log(contents);
}, 5000);
Output:

35 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Exercise-7
7. AIM:Implement routing for the AdventureTrails application using Nodde.js.

Source code:

const express = require('express');


const app = express();

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

// Attach the router to the base URL '/adventuretrails'


app.use('/adventuretrails', routes);

// Start the server


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

const express = require('express');


const router = express.Router();

// Define routes
router.get('/', (req, res) => {
res.send('Welcome to AdventureTrails!');
});

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


res.send('Here are the available trails.');
});

router.get('/trails/:id', (req, res) => {


const id = req.params.id;
res.send(`Trail with ID ${id} is selected.`);
});

// Export router
module.exports = router;

36 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Output:

37 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

7b. AIM:In my notes application: (i) we want to handle POST submissions. (ii) display
customized error messages. (iii) perform logging.

Source code:
const express = require('express');
constbodyParser = require('body-parser');
const morgan = require('morgan');

const app = express();

// Use the morgan middleware for logging


app.use(morgan('combined'));

// Use the bodyParser middleware for parsing request bodies


app.use(bodyParser.json());

// Define a route for the homepage


app.get('/', (req, res) => {
res.send('Welcome to myNotes!');
});

// Define a route for the 'about' page


app.get('/about', (req, res) => {
res.send('About myNotes');
});

// Define a route for handling POST requests to /notes


38 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

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


const note = req.body.note;
if (!note) {
// Return an error message if the note field is missing or empty
return res.status(400).send('Note is required');
}
// Save the note and return a success message
// TODO: implement the saveNote function
saveNote(note);
res.send('Note saved successfully');

});
const fs = require('fs');
constaccessLogStream = fs.createWriteStream('access.log', { flags: 'a' });
app.use(morgan('combined', { stream: accessLogStream }));

// Start the server


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

// Function for saving notes (dummy implementation)


function saveNote(note) {
console.log(`Saving note: ${note}`);
}
app.get('/', (req, res) => {
39 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

res.render('index');
});
app.set('view engine', 'ejs');

Output:

40 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

41 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

7c.AIM: Write a program to wrap the Schema into a Model object in express.js.

Source code:
const mongoose = require('mongoose');

// Define the schema


constuserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
age: {
type: Number,
min: 18,
max: 100,
default: 18
},
email: {
type: String,
required: true,
unique: true,
match: /^\S+@\S+\.\S+$/
}
});

// Create the model


const User = mongoose.model('User', userSchema);

42 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

// Connect to the database


mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err =>console.error('Could not connect to MongoDB', err));

// Create a new user


const user = new User({
name: 'John Doe',
email: '[email protected]'
});

// Save the user to the database


user.save()
.then(() => console.log('User saved to database'))
.catch(err =>console.error('Could not save user to database', err));

43 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Output:

44 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Exercise-8
8. AIM: Write a program to perform various CRUD (Create-Read-Update-Delete)
operations using Mongoose library functions.

Source code:

const express = require('express');


const mongoose = require('mongoose');

// Connect to the database


mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err =>console.error('Could not connect to MongoDB', err));

// Define the schema


constnoteSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
content: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});

// Create the model


const Note = mongoose.model('Note', noteSchema);

// Create an express app


const app = express();

// Parse JSON requests


app.use(express.json());

// Define routes
app.get('/notes/:id', async (req, res) => {
45 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

try {
const note = await Note.findById(req.params.id);
if (!note) return res.status(404).send('Note not found');
res.send(note);
} catch (err) {
console.error(err);
res.status(500).send('Server error');
}
});

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


try {
const note = await Note.findByIdAndUpdate(req.params.id, {
title: req.body.title,
content: req.body.content
}, { new: true });
if (!note) return res.status(404).send('Note not found');
res.send(note);
} catch (err) {
console.error(err);
res.status(500).send('Server error');
}
});

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


try {
const note = new Note({
title: req.body.title,
content: req.body.content
});
await note.save();
res.send(note);
} catch (err) {
console.error(err);
res.status(500).send('Server error');
}
});

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


try {
const note = await Note.findByIdAndDelete(req.params.id);
if (!note) return res.status(404).send('Note not found');
res.send(note);
46 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

} catch (err) {
console.error(err);
res.status(500).send('Server error');
}
});

// Start the server


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

Output:

47 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

//API Development
Output :

API 1

API 2

48 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

API 3

API 4

API 5

8b. AIM:Write a program to explain session management using cookies and sessions.
49 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Source code:
const express = require('express');
const session = require('express-session');
constuuid = require('uuid').v4;

const app = express();

// Enable sessions
app.use(session({
secret: 'mysecretkey',
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true }
}));

// Define routes
app.get('/', (req, res) => {
constsessionId = req.session.id;
res.send(`Session ID: ${sessionId}`);
});

// Start the server


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

50 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Output:

51 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

//Write a program to explain session management using cookies


const express = require('express');
constcookieParser = require('cookie-parser');
constuuid = require('uuid').v4;
const app = express();
// Enable cookie parsing
app.use(cookieParser());
// Define a middleware to create a session ID cookie if none exists
app.use((req, res, next) => {
if (!req.cookies.sessionId) {
constsessionId = uuid();
res.cookie('sessionId', sessionId, { httpOnly: true });
}
next();
});
// Define routes
app.get('/', (req, res) => {
constsessionId = req.cookies.sessionId;
res.send(`Session ID: ${sessionId}`);
});
// Start the server
app.listen(3000, () => console.log('Server started on port 3000'));

Output:

52 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Exercise-9
9.AIM:On the page, display the price of the mobile-based in three different colors by
using Typescript.
Source code:
<!doctype html>
<html>
<head>
<title>Mobile Cart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet">
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></scrip
t> 10.
<style>
.navbar-inverse {
background-color:#005580;
background-image: none;
background-repeat: no-repeat;
color:#ffffff;
}
.navbar-inverse .navbar-nav > .active > a {
color: #ffffff;
background-color:transparent;
}
.navbar-inverse .navbar-nav > li > a:hover{
text-decoration: none;
color: #ffffff;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
53 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-
target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Mobile Cart</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="#">Home</a></li>
</ul>
<!--/.nav-collapse -->
<ul class="nav navbar-nav navbar-middle" style="color:white; margin-right:30px;">
<li><a href="Cart.html"><span class="glyphiconglyphicon-shopping-cart"
style="color:white"></span></a></li>
</ul>
</div>
</nav>
<div style="margin-top:7%">
<center><h2>Your Favorite Online Mobile Shop!</h2></center>
</div>
<div class="container" style="padding-top:5%">
<div class="row">

<div class="col-md-4">
<div style="text-align: center;">
<imgsrc="Images/Part 1/SamsungGalaxy_Gold.jpg" height="250px">
</div>
<div style="padding-top:10px;">
<div onclick="getMobileDetails();" style="cursor:pointer;color:Steelblue;text-align:
center;"><b><span id="pName0"></span></b></div>
<div style="padding-top:10px;padding-left:
101px;"><b>Price:</b>&nbsp;&dollar;<span id="pPrice0"></span></div>

54 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

<div style="padding-left: 100px;"><b>Status:</b><span


id="pAvailable0"></span></div>
</div>
</div>
<div class="col-md-4">
<div style="text-align: center;">
<imgsrc="Images/Part 1/samsung_edge_silver.jpg" height="250px">
</div>
<div style="padding-top:10px;">
<div onclick="getMobileDetails('samsungedge',231);"
style="cursor:pointer;color:Steelblue;text-align: center;"><b><span
id="pName1"></span></b></div>
<div style="padding-top:10px;padding-left:
95px;"><b>Price:</b>&nbsp;&dollar;<span id="pPrice1"></span></div>
<div style="padding-left: 94px;"><b>Status:</b><span
id="pAvailable1"></span></div>
</div>
</div>
<div class="col-md-4">
<div style="text-align: center;">
<imgsrc="Images/Part 1/lumia_640xl.jpg" height="250px">
</div>
<div style="padding-top:10px;">
<div onclick="getMobileDetails('lumia',875);"
style="cursor:pointer;color:Steelblue;text-align: center; "><b><span
id="pName2"></span></b></div>
<div style="padding-top:10px;padding-left:
118px;"><b>Price:</b>&nbsp;&dollar;<span id="pPrice2"></span></div>
<div style="padding-left: 117px;"><b>Status:</b><span
id="pAvailable2"></span></div>
</div>
</div>
</div>
</div>
</body>
<!--Adding the converted js file -->
<script src="arrays.js"></script>
55 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

</html>

Output:

56 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

// declaring an Array with 3 objects


const manufacturers = [{ id: 'Samsung', price: 150 },
{ id: 'Microsoft', price: 200 },
{ id: 'Apple', price: 400 },
{ id: 'Micromax', price: 100 }
];
let test;
// Arrow function to populate the details of Array whose price is greater than 200
function myFunction() {
test = manufacturers.filter((manufacturer) =>manufacturer.price>= 200);
}
// self-invoking an arrow function myFunction();
console.log('Details of Manufacturer array are : ');
// logic to populate the manufacturer array details based on id value for (const item
of test) {
console.log(item.id);

57 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

// declaring a function which accepts string datatype as parameter and returns string array
function
getMobileByManufacturer(manufacturer: string): string[] {
let mobileList: string[];
if (manufacturer === 'Samsung') {
mobileList = ['Samsung Galaxy S6 Edge', 'Samsung Galaxy Note 7', 'Samsung Galaxy J7 SM-
J700F'];
return mobileList;
} else if (manufacturer === 'Apple') {
mobileList = ['Apple iPhone 5s', 'Apple iPhone 6s ', 'Apple iPhone 7'];
return mobileList;
} else {
mobileList = ['Nokia 105', 'Nokia 230 Dual Sim'];
return mobileList;
}
}

58 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

<!doctype html>
<html>
<head>
<title>Mobile Cart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.navbar-inverse {
background-color: #005580;

background-image: none;
background-repeat: no-repeat;
color: #ffffff;
}

.navbar-inverse .navbar-nav>.active>a {
color: #ffffff;
background-color: transparent;
}
.navbar-inverse .navbar-nav>li>a:hover {
text-decoration: none;
color: #ffffff;
}
</style>
</head>

59 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-
target="#navbar"
aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Mobile Cart</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="#">Home</a></li>
</ul>
<!--/.nav-collapse -->
<ul class="nav navbar-nav navbar-middle" style="color:white; margin-right:30px;">
<li><a href="Cart.html"><span class="glyphiconglyphicon-shopping-cart"
style="color:white"></span></a>
</li>
</ul>
</div>
</nav>
<div style="margin-top:7%">

<center>
<h2>Your Favorite Online Mobile Shop!</h2>
</center>
</div>

60 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

<div class="container" style="padding-top:5%">


<div class="row">
<div class="col-md-4">
<div style="text-align: center;">
<imgsrc="images/SamsungGalaxy_Gold.jpg" height="250px">
</div>
<div style="padding-top:10px;">
<div onclick="getMobileDetails();" style="cursor:pointer;color:Steelblue;text-align: center;">
<b><span id="pName0">Samsung Galaxy Note 7</span></b></div>
<div style="padding-top:10px;padding-left: 101px;"><b>Price:</b>&nbsp;&dollar;<span
id="pPrice0">699</span></div>
<div style="padding-left: 100px;"><b>Status:</b><span
id="pAvailable0">Available</span></div>
</div>
</div>
<div class="col-md-4">
<div style="text-align: center;">
<imgsrc="images/samsung_edge_silver.jpg" height="250px">
</div>
<div style="padding-top:10px;">
<div onclick="getMobileDetails('samsungedge',231);"
style="cursor:pointer;color:Steelblue;text-align: center;"><b><span id="pName1">Samsung
Galaxy
S6 Edge</span></b></div>
<div style="padding-top:10px;padding-left: 95px;"><b>Price:</b>&nbsp;&dollar;<span
id="pPrice1">630</span></div>
<div style="padding-left: 94px;"><b>Status:</b><span
id="pAvailable1">Available</span></div>
</div>
</div>
<div class="col-md-4">

61 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

<div style="text-align: center;">


<imgsrc="images/lumia_640xl.jpg" height="250px">
</div>
<div style="padding-top:10px;">

<div onclick="getMobileDetails('lumia',875);"
style="cursor:pointer;color:Steelblue;text-align: center; "><b><span id="pName2">Nokia
Lumia 89. 640XL</span></b></div>
<div style="padding-top:10px;padding-left: 118px;"><b>Price:</b>&nbsp;&dollar;<span
id="pPrice2">224</span></div>
<div style="padding-left: 117px;"><b>Status:</b><span id="pAvailable2">Out of
Stock!</span></div>
</div>
</div>
</div>
</div>
</body>
<!-- Adding the converted js file -->
<script src="productlist.js"></script>
</html>

62 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Output:

63 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Attach the transpiled TypeScript file to the HTML page as highlighted in the above code.
ProductDetail.html:
<!doctype html>
<html>
<head>
<title>Mobile Cart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet">
<style>
.navbar-inverse {
background-color: #005580;
background-image: none;
background-repeat: no-repeat;
color: #ffffff;
}
.navbar-inverse .navbar-nav>.active>a {
color: #ffffff;
background-color: transparent;
}
.navbar-inverse .navbar-nav>li>a:hover {
text-decoration: none;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">.
<div class="navbar-header">
64 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"


data-target="#navbar"
aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Mobile Cart</a>
</div>
<div id="navbar" class="collapse navbar-collapse">

<ul class="nav navbar-nav">


<li><a href="Index.html">Home</a></li>
</ul>
<!--/.nav-collapse -->
<ul class="nav navbar-nav navbar-middle" style="color:white; margin-
right:30px;">
<li><a href="Cart.html"><span class="glyphiconglyphicon-shopping-cart"
style="color:white"></span></a>
</li>
</ul>
</div>
</nav>
<div class="container" style="margin-top:7%">
<div class="row">
<div class="col-sm-4">
65 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

<div style="margin-left:40%;padding-top:15px;">
<div style="padding:15px;">
<div>
<img id="phoneImage" src="Images/Part 1/SamsungGalaxy_Gold.JPG"
height="250px">
</div>
<div style="padding-top:10px;">
<div><b><span id="pName"></span></b></div>
<div style="padding-top:10px;"><b>Price:</b>&nbsp;&dollar;<span
id="pPrice"></span></div>
<div><b>Status:</b>&nbsp;<span id="pAvailable"></span></div>
<div><b class="text-danger">Discount:</b>&nbsp;<span
id="pDiscount"></span></div>
</div>
</div>
</div>
</div>
<div></div>
<div style="padding-top:15px;">
<div>
<imgsrc="Images/Part 1/goldmobile.png" style="padding-
left:15px;cursor:pointer;"
onclick="getMobileByColor('gold');">
<imgsrc="Images/Part 1/pinkmobile.png" style="cursor:pointer;padding-
left:15px;"
onclick="getMobileByColor('pink');">
<imgsrc="Images/Part 1/silvermobile.png" style="cursor:pointer;padding-
left:15px;"
66 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

onclick="getMobileByColor('silver');">
</div>
<div style="padding-top:10px;">

<span style="padding-left:20px;">
GoldPlatinum
</span>
<span style="padding-left:38px;">
PinkGold
</span>
<span style="padding-left:40px;">
SilverTitanium
</span>
</div>
<div style="padding-top:10px;">
<span style="padding-left: 20px;">&dollar;</span><span id="gold"
style="padding-left: 2px;"></span>
. <span style="padding-left: 90px;">&dollar;</span><span id="pinkgold"
style="padding-left: 2px;"></span>
<span style="padding-left: 65px;">&dollar;</span><span id="silver"
style="padding-left: 2px;"></span>
<div id="productDescription" style="padding-top:5%;width:70%;text-
align:justify">
Samsung Galaxy Note 7 is a stylish mobile you can ever have. It has 64GB
memory.
</div>
<div style="padding-top:5%;padding-right:10%">
67 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

<button class="btnbtn-success" onclick="addtoCart();">Add to Cart</button>


<a style="padding-left:10px;" onclick="backHome();">Back</a>
</div>
</div>
</div>
</div>
</div>
</body>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></sc
ript>
<!-- Adding converted js code-->
<script src="productdetail.js"></script>
</html>

Output:

68 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Exercise-10
10.AIM:Implement business logic for adding multiple Product values
into a cart variable which is a type of string array.

Source code:-
// declaring a empty string array const cart: string[] = [];
// arrow function logic to push values into cart array constpushtoCart = (item: string)
=>{ cart.push(item); };
// logic to add items into cart
function addtoCart(...productName: string[]): string[] {
for (const item of productName) { pushtoCart(item);
}
return cart;
}
// to populate value on console
console.log('Cart Items are:' + addtoCart(' Moto G Play, 4th Gen', ' Apple iPhone 5s'));

69 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

// declaring an interface
interface Product {
productId: number ;
productName: string ;
}
// logic to display the Product details with interface object as parameter function
getProductDetails(productobj: Product): string {
return 'The product name is : ' + productobj.productName;
}
// declaring a variable having interface properties
constprodObject = {productId: 1001, productName: 'Mobile'};
// declaring variable and invoking Product details function constproductDetails: string
= getProductDetails(prodObject);
// line to populate the created product on console console.log(productDetails);

70 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

//declaring afunction
function CreateCustomerID(name: string, id:
number): string
{return'Thecustomeridis'+name + ''+ id;
}

// declaring a interface
with function typeinterface
StringGenerator{

(chars:string,nums:number):string;
}

//creatingreferencevariableofabovedeclar
edinterfaceletidGenerator:StringGenerator;

//assignmentoffunctiontointerfacereferencevaria
bleidGenerator = CreateCustomerID;

//declaringastringparametertoholdreturnvalueoffunctiontypei
nterfaceconstcustomerId: string=idGenerator('Mr.Tom', 101);

// line to populate the Customer


Detailsconsole.log(customerId);

71 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Exercise-11
11.AIM:To create a variable of extends properties interface type.
Source code:
// declaring a Category interface interface Category {
categoryName: string;
}
// declaring a Product interface interface Product {
productName: string; productId: number;
}
// declaring a ProductList interface which is extends from Category and Product interfaces interface
ProductList extends Category, Product {
list: Array<string>;
}
// declaring a variable which is type of ProductList interface const productDetails: ProductList = {
categoryName: 'Gadget', productName: 'Mobile', productId: 1234,
list: ['Samsung', 'Motorola', 'LG']
};
// assigning list value of productDetails variable into another variable const listProduct = productDetails.list;
// assigning productName value of productDetails variable into another variable const pname: string =
productDetails.productName;
// line to populate Product name console.log('Product Name is ' + pname);

// line to populate Product list console.log('Product List is ' + listProduct);

72 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

// declaring a Product interface


interface Product {
displayProductName: (prouctId: number) => string;
getProductDetails(): string[];
}
// declaring Gadget class which implements Product interface
class Gadget implements Product {
getProductDetails(): string[] {
return ['Samsung', 'LG', 'Moto'];
}
displayProductName(productId: number): string { if (productId === 101) {
return 'Product Name is Mobile';
} else if ( productId === 201) {
return 'Product Name is Tablet';
}
}
getGadget(): string[] {
return ['Mobile', 'Tablet', 'iPad', 'iPod'];
}
}
// creating instance of class of interface type
const gadget: Product = new Gadget();
// creating variable to hold return value of displayProductName function const
productName: string = gadget.displayProductName(101);
// line to populate Product name on console

73 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

console.log(productName);

// declaring a Product class class Product {

static productPrice: string;


productId: number;
// constructor declaration constructor(productId: number) {
this.productId = productId;
}
getProductId(): string {
return 'Product id is : ' + this.productId;
}
}
// creation of Product class object
const product: Product = new Product(1234);
// line to populate the product id details
console.log(product.getProductId());

// declaring a Product class with access modifiers

74 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

class Product {
static productPrice = 150;
private productId: number;
public productName: string;
protected productCategory: string;
// declaration of constructor with 3 parameters
constructor(productId: number, productName , productCategory) {
this.productId = productId;
this.productName = productName
this.productCategory = productCategory;
}
// method ot display product id details getProductId() {
console.log('The Product id is : ' + this.productId);
}
}
// declaring a Gadget class extending the properties from Product class
class Gadget extends Product {
// method to display productCategory property getProduct(): void {
console.log('Product category is : ' + this.productCategory);
}
}
// Gadget Class object creation
const g: Gadget = new Gadget(1234, 'Mobile', 'SmartPhone');
// invoking getProduct method with the help of Gadget object
g.getProduct();
// invoking getProductId method with the help of Gadget object
g.getProductId();
// line to populate product name property with Gadget object
console.log('Product name is : ' + g.productName);
75 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

// line to populate static property product price directly with Product class name
console.log('Product price is : $' + Product.productPrice);

76 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Exercise-12
12.AIM:Create a Product class with 4 properties namely productId and methods
setProductId()andgetProductId().

Source code:
Create a file namespace_demo.ts
namespace Utility {
export namespace Payment {
export function CalculateAmount(price: number, quantity: number): number {
return price * quantity; 5. }
} export function MaxDiscountAllowed(noOfProduct: number): number {
if (noOfProduct> 5) {
return 40;
} else {
return 10;
}
}functionprivateFunc(): void {
console.log('This is private...');
}
}
Step 2: Create another file Namespace_import.ts
/// <reference path="./namespace_demo.ts" />
import util = Utility.Payment;
let paymentAmount = util.CalculateAmount(1255, 6);
console.log(`Amount to be paid: ${paymentAmount}`);
let discount = Utility.MaxDiscountAllowed(6);
onsole.log(`Maximum discount allowed is: ${discount}`);

77 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

Step 4: Run node Final.js from the command line

export function MaxDiscountAllowed(noOfProduct: number): number {


if (noOfProduct> 5) {
return 30;
} else {
return 10; 6. }
} class Utility {
CalculateAmount(price: number, quantity: number): number {
return price * quantity;
}
}
interface Category {
getCategory(productId: number): string;
}
export const productName = 'Mobile';
export {Utility, Category};
Step 2: Create another file 2.module_import.ts
import { Utility as mainUtility, Category, productName, MaxDiscountAllowed } from
"./module_demo";
const util = new mainUtility();
const price = util.CalculateAmount(1350, 4); 4.

78 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT


20B61A4511 Dept.of Computer Science & Engineering

const discount = MaxDiscountAllowed(2);


console.log(`Maximum discount allowed is: ${discount}`); 7.
console.log(`Amount to be paid: ${price}`);
console.log(`ProductName is: ${productName}`);
Step 3: Open a command prompt and navigate to the folder in which module files
resides and run thebelowcommand fromthecommandline

Step4:Runnode2.module_import.jsfromthecommandline.

// declaring Generic function named printData


function printData<T>( data: T): T {
return data;
}
// variable declaration to access Generic function
const stringData: string = printData<string>('Hello Generics');
// line to populate the result of Generic function on console.
console.log('String data ' + stringData);

79 | P a g e

SATYA INSTITUTE OF TECHNOLOGY AND MANAGEMENT

You might also like