0% found this document useful (0 votes)
81 views85 pages

MEAN STACK (AutoRecovered)

Uploaded by

Ashok Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views85 pages

MEAN STACK (AutoRecovered)

Uploaded by

Ashok Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 85

Mean Full Stack Lab Manual

Experinment-1a:
Aim:
Include the Metadata element in Homepage.html for providing description as "IEKart's is an online
shopping website that sells goods in retail. This company deals with various categories like Electronics,
Clothing, Accessories etc.
DESCRIPTION:

Case-insensitivity: HTML is case-insensitive, meaning that tags and attributes can be written in uppercase or
lowercase letters and will still be recognized by the browser.

Platform-independency: HTML is platform-independent, meaning that it can be viewed on any device or operating
system with a web browser.

DOCTYPE Declaration: The DOCTYPE declaration is used at the beginning of an HTML document to specify the
version of HTML being used and to ensure that the document is rendered correctly by web browsers.

Types of Elements: HTML has several types of elements, including structural elements (such as <html>, <head>,
and <body>), text-level elements (such as <p> and <span>), and multimedia elements (such as <img>, <audio>,
and <video>).

HTML Elements - Attributes: HTML elements can be customized with attributes, which provide additional
information about the element and how it should be displayed or used. Examples of attributes include "class" for
defining CSS styles, "id" for identifying a specific element, and "href" for specifying a hyperlink.

Metadata Element: The metadata element (<meta>) is used to provide information about the HTML document that
is not displayed in the browser window. This includes information such as the author, description, and keywords,
which can be used by search engines to index and display the webpage in search results.

Source Code:

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Meta tag example</title>
<!-- Specifies the character encoding for the document. -->
<!-- ISO-8859-1 -->
<meta charset="utf-8">
<meta name="author" content="Susan">
<meta name="description" content="This is a sample demo to understand HTML.">
<!-- A web app wants to allow content from a current domain and truste domain xyz
and all its subdomains -->
<meta http-equiv="content-security-policy" content="default-src 'self' http://xyz.com" >
<!-- Specify the preferred style sheet to use.-->
<meta http-equiv="default-style" content="/style.css">
<!-- page content display to be adjusted to the device width being used to view the content with initial
zoom level as 100% -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p> Sample demo to explain meta tag with attributes </p>
</body>
</html>
Mean Full Stack Lab Manual
Output:

Experinment-1b:
Aim:
Enhance the Homepage.html of IEKart's Shopping Application by adding appropriate sectioning
elements.

DESCRIPTION:

Sectioning elements in HTML are used to divide the content of a web page into logical sections, making it easier
for users to understand and navigate the content. These elements include <header>, <nav>, <section>, <article>,
<aside>, and <footer>. The <header> element is used to identify the header section of a page, while the <nav>
element is used to define a set of navigation links.

Source Code:

<!DOCTYPE html>
<html>
<body>
<header>
<nav> Login | SignUp</nav>
<h1> Brand Name </h1>
</header>
<article>
<section>
<p>Paragraph 1</p>
<p>Paragraph 2 is thematically related to Paragraph 1</p>
</section>
</article>
<aside>

Side info
</aside>
<footer>
<nav> About Us | Contact Us </nav>
</footer>
Mean Full Stack Lab Manual
</body>
</html>

Output:

Experinment-1c:
Aim:
Make use of appropriate grouping elements such as list items to "About Us" page of IEKart's
Shopping Application

Description:
Paragraph Element: The <p> element is used to define a paragraph of text in HTML.

Division and Span Elements: The <div> and <span> elements are used to group elements and apply styles or
classes to them. The <div> element is a block-level element, while the <span> element is an inline-level element.

Simatic Element: The <article>, <header> , <header> , <aside>, <footer> and <nav>

Source Code:

<!DOCTYPE html>
<html>

<head>

<title>Ekart Shopping</title>
<meta name="keywords" content="Online, Shopping" />
</head>

<body>
<header>
<nav> Login | SignUp | Track order </nav>
<h1> Welcome to Ekart Shopping </h1>
Mean Full Stack Lab Manual
<nav> Electronics | Books | Sports | Media | Clothing | Offers Zone </nav>
</header>
<article>
<h2>About Us</h2>Ekart Shopping is one among the world wide on-line products dealer.
<section>!--Include list items here--!</section>
</article>
<footer>
<nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav> Copyright 2018
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>

</html>

Output:

Experinment-1d:
Aim:
Link "Login", "SignUp" and "Track order" to "Login.html", "SignUp.html" and "Track.html" page
respectively. Bookmark each category to its details of IEKart's Shopping application.
Description:

In HTML, the <a> tag is used to create hyperlinks, allowing users to navigate to another webpage when they
click on it. To link to an external page, you need to specify the URL of the external page within the href attribute
of the <a> tag. Here's an example:
Source Code:

<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="Online, Shopping" />
<title>Ekart Shopping</title>
</head>
<body>
<header>
<nav>
<a href="Login.html"> Login </a> | <a href="Signup.html">SignUp</a> |<a
Mean Full Stack Lab Manual
href="TrackOrder.html"> Track order </a>
</nav>
<h1>Welcome to Ekart Shopping</h1>
<nav>
<a href="#Clothing"> Clothing </a> | <a href="#Media"> Media </a>
</nav>
</header>
<article>Ekart& Co very own one-stop solution for all your shopping needs!
<br/>
Dont believe us? Click on the offers
and check it out for yourself !!
<h2 id="Clothing"> Clothing </h2>
<h2 id="Media"> Media </h2>
</article>
<footer>
<nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav> Copyright
<!-- Add character entity for Copyright symbol -->2018 | Giri
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>
</html>

Output:

Experinment-1e:

Aim:
Add the © symbol in the Home page footer of IEKart's Shopping application
Description:
In HTML, character entities are special codes used to represent special characters that are not part
of the standard character set. These entities are defined by their unique entity name or a numeric
code and are used to display symbols, foreign characters, mathematical symbols, and more.
Examples of character entities include <for < + > for > , and & for &.

Source Code:

<!DOCTYPE html>
Mean Full Stack Lab Manual
<html>
<head>
<meta name="keywords" content="Online, Shopping" />
<title>Ekart Shopping</title>
</head>

<body>
<header>
<nav>
<a href="Login.html"> Login </a> | <a href="Signup.html">SignUp</a> |<a
href="TrackOrder.html"> Track order </a>
</nav>
<h1>Welcome to Ekart Shopping</h1>
<nav>
<a href="#Clothing"> Clothing </a> | <a href="#Media"> Media </a>
</nav>
</header>
<article>Ekart& Co very own one-stop solution for all your shopping needs !
<br />
Dont believe us? Click on the offers
and check it out for yourself !!
<h2 id="Clothing"> Clothing </h2>
<h2 id="Media"> Media </h2>
</article>
<footer>
<nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav> Copyright
&copy;2018 | Giri
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>
</html>

Output:
Mean Full Stack Lab Manual

Experinment-1f:
Aim:
Add the global attributes such as contented table, spellcheck, id etc. to enhance the Signup Page
functionality of IEKart's Shopping application.

Description:
HTML5 Global Attributes are attributes that can be used on any HTML element and are not limited to specific
elements. These attributes can be used to provide additional information about an element, such as defining the
class or id, setting styles, and assigning event handlers. Some commonly used global attributes include "class",
"id", "style". "title", and "data-"".

Source Code:

<!DOCTYPE html>
<html>

<head>
<meta name="keywords" content="Online, Shopping" />
<title>Ekart Shopping</title>
</head>

<body>
<header>
<h1>Sign Up!</h1>
</header>
<article>
<form action="success.html" method="get">
<table>
<tr>
<td><br><label for="username">Username:</label></td>
<td><br><input type="text" id="username" placeholder="Enter your username" required
</tr>
<tr>
<td><label for="email_id">Email ID:</label></td>
<td><input type="email" id="email_id" placeholder="Enter your email ID" required /></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" id="password" placeholder="Enter your password" required

</tr>
<tr>
<td><label for="gender">Gender:</label></td>
<td><label for="male">Male<input type="radio" id="male" name="gender" value="M"

/>&nbsp; <label for="female">Female<input


type="radio" id="female" name="gender" value="F" /></td>
</tr>
<tr>
Mean Full Stack Lab Manual
<td><label for="dob">DOB:</label></td>
<td><input type="date" id="dob" required /></td>
</tr>
<tr>
<td><label for="phone_no">Phone number:</label></td>
<td><input type="text" id="phone_no" placeholder="Enter your contact number" pattern="+ [0-9]
{12}" required /></td>
</tr>
<tr>
<td><label for="country">Country:</label></td>
<td><select id="country" placeholder="Select your country">
<option value="India" />India
<option value="India" />USA
<option value="India" />UK
<option value="India" />Canada
<option value="India" />Belgium
<option value="India" />France </select></td>
</tr>
<tr>
<td><label id="language">Languages Known:</label></td>
<td><input type="checkbox" name="language" id="english" value="English"
checked="checked" /><label for="english">
English </label><input type="checkbox" name="language" id="hindi" value="Hindi"
/><label for="hindi"> Hindi
</label><input type="checkbox" name="language" id="french" value="French" /><label
for="french"> French </label></td>
</tr>
<tr>
<td><label for="pic">Profile pic:</label></td>
<td><input type="file" id="pic" required /></td>
</tr>
<tr>
<td><label for="yourself" dir="ltr">About yourself:</label></td>
<td><textarea></textarea></td><!-- Add contenteditable and spellcheck attribute -->
</tr>
<tr>
<td><input type="submit" value="Register" />
<td><input type="reset" value="Reset" />
</tr>
</table>
</form><br /><br /><br /><br />
</article>
<footer>
<nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav> Copyright &copy;
2018 | Giri
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>

</html>
Mean Full Stack Lab Manual

Output:

Experinment-2a:
Aim:
Enhance the details page of IEKart's Shopping application by adding a table element to display the
available mobile/any inventories.
Description:

Table elements in HTML are used to display data in a tabular format and can be customized using attributes such
as colspan/rowspan, border, cellspacing, and cellpadding

Source Code:

<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="Online, Shopping" />
<title>Ekart Shopping</title>
</head>

<body>
<div id="tab">
<table border="1" id="tables">
<caption>Electronics</caption>
Mean Full Stack Lab Manual
<tr>
<td>SmartWatches& Fitness trackers</td>
<td><img src="https://www.topbestproreview.com/wp-content/uploads/2018/01/9-8.jpg"
style="width: 75px;height: 75px;" alt="watch Pic"></td>
</tr>
<tr>
<td>Earbuds</td>
<td><img src="https://th.bing.com/th/id/OIP._- SxrRgB9pImgyaQ4mN5fwHaHa?
pid=ImgDet&rs=1" style="width: 75px;height: 75px;" alt="buds Pic"></td>
</tr>
<tr>
<td>Speakers</td>
<td><img src="https://tomantosfilms.com/wp-content/uploads/2015/11/Behringer-MS40-v2.jpg"
style="width: 75px;height: 75px;" alt="Speakers Pic"></td>
</tr>
</table>
</div>
</body>
</html>
Output:

Experinment-2b:
Aim:
Using the form elements create Signup page for IEKart's Shopping application.
Description:
Form elements in HTML are used to collect user input and can be customized with various attributes such as
input type, name, placeholder, and required. The color and date pickers allow users to choose colors and dates
from a graphical interface, while select and datalist elements provide a dropdown menu for users to select from a
pre-defined list of options

Source Code:

<!DOCTYPE html>
<html>

<head>
Mean Full Stack Lab Manual
<meta name="keywords" content="Online, Shopping" />
<title>Ekart Shopping</title>
</head>

<body>
<header>
<h1>Sign Up!</h1>
</header>
<article>
<form action="success.html" method="get">
<table>
<tr>
<td><br><label for="username">Username:</label></td>
<td><br><input type="text" id="username" placeholder="Enter your username" required
</tr>
<tr>
<td><label for="email_id">Email ID:</label></td>
<td><input type="email" id="email_id" placeholder="Enter your email ID" required /></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" id="password" placeholder="Enter your password" required

</tr>
<tr>
<td><label for="gender">Gender:</label></td>
<td><label for="male">Male<input type="radio" id="male" name="gender" value="M"

/>&nbsp; <label for="female">Female<input


type="radio" id="female" name="gender" value="F" /></td>
</tr>
<tr>
<td><label for="dob">DOB:</label></td>
<td><input type="date" id="dob" required /></td>
</tr>
<tr>
<td><label for="phone_no">Phone number:</label></td>
<td><input type="text" id="phone_no" placeholder="Enter your contact number" pattern="+ [0-9]
{12}" required /></td>
</tr>
<tr>
<td><label for="country">Country:</label></td>
<td><select id="country" placeholder="Select your country">
<option value="India" />India
<option value="India" />USA
<option value="India" />UK
<option value="India" />Canada
<option value="India" />Belgium
<option value="India" />France </select></td>
</tr>
<tr>
<td><label id="language">Languages Known:</label></td>
Mean Full Stack Lab Manual
<td><input type="checkbox" name="language" id="english" value="English"
checked="checked" /><label for="english">
English </label><input type="checkbox" name="language" id="hindi" value="Hindi"
/><label for="hindi"> Hindi
</label><input type="checkbox" name="language" id="french" value="French" /><label
for="french"> French </label></td>
</tr>
<tr>
<td><label for="pic">Profile pic:</label></td>
<td><input type="file" id="pic" required /></td>
</tr>
<tr>
<td><label for="yourself" dir="ltr">About yourself:</label></td>
<td><textarea></textarea></td><!-- Add contenteditable and spellcheck attribute -->
</tr>
<tr>
<td><input type="submit" value="Register" />
<td><input type="reset" value="Reset" />
</tr>
</table>
</form><br /><br /><br /><br />
</article>
<footer>
<nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav> Copyright &copy;
2018 | Giri
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>

</html>

Output:

Experinment-2c:
Aim:
Mean Full Stack Lab Manual
Enhance Signup page functionality of IEKart's Shopping application by adding attributes to input
elements.
Description:
elements in HTML are used to collect user input and can be customized using various attributes such as type,
name, value, placeholder, autofocus, required, disabled, and read-only. These attributes provide additional
functionality and control over how users can interact with the input element. For example, the type attribute can
specify whether the input should be a text box, checkbox, radio button, or other types of input. The required
attribute can indicate that the user must provide input in order to submit the form, while the read-only attribute
can indicate that the user cannot modify the input value

Source Code:

<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="Online, Shopping" />
<title>Ekart Shopping</title>
</head>
<body>
<header>
<h1>Sign Up!</h1>
</header>
<article>
<form>
<table>
<tr>
<td><br><label>Username:</label></td>
<td><br><input type="text" id="username" placeholder="Enter your username" required

</tr>
<tr>
<td><label>Email ID:</label></td>
<td><input type="email" id="email_id" placeholder="Enter your email ID" required /></td>
</tr>
<tr>
<td><label>Password:</label></td>
<td><input type="password" id="password" placeholder="Enter your password" required

</tr>
<tr>
<td><label>Gender:</label></td>
<td><label for="male">Male<input type="radio" id="male" name="gender" value="M"

/>&nbsp; <label for="female">Female<input


type="radio" id="female" name="gender" value="F" /></td>
</tr>
<tr>
<td><label>DOB:</label></td>
<td><input type="date" id="dob" required /></td>
</tr>
<tr>
<td><label>Phone number:</label></td>
Mean Full Stack Lab Manual
<td><input type="text" id="phone_no" placeholder="Enter your contact number" pattern="[0-
9]+"maxlength="10 required /></td>

</tr>
<tr>
<td><label>Country:</label></td>
<td><select id="country" placeholder="Select your country">
<option value="India" />India
<option value="India" />USA
<option value="India" />UK
<option value="India" />Canada
<option value="India" />Belgium
<option value="India" />France</select></td>
</tr>
<tr>
<td><label id="language">Languages Known:</label></td>
<td><input type="checkbox" name="language" id="english" value="English"
checked="checked" /><label for="english">
English </label><input type="checkbox" name="language" id="hindi" value="Hindi"
/><label for="hindi"> Hindi
</label><input type="checkbox" name="language" id="french" value="French" /><label
for="french"> French </label></td>
</tr>
<tr>
<td><label for="pic">Profile pic:</label></td>
<td><input type="file" id="pic" required /></td>
</tr>
<tr>
<td><input type="submit" value="Register" />
<td><input type="reset" value="Reset" />
</tr>
</table>
</form><br /><br /><br /><br />
</article>
<footer>
<nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav> Copyright &copy;
2018 | Giri
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>

</html>
Output:
Mean Full Stack Lab Manual

Experinment-2d:
Aim:
Add media content in a frame using audio, video, iframe elements to the Home page of IEKart's
Shopping application.
Description:
Media elements are used to embed multimedia content such as audio and video into a webpage iframe elements
are used to embed external content such as web pages or maps directly into a webpage, and can be customized
with attributes like "src" and "scrolling."

Source Code:

<!

DOCTYPE html>
<html>
<head>
<meta name="keywords" content="Online, Shopping" />
Mean Full Stack Lab Manual
<title>Ekart Shopping</title>
</head>
<body>
<header>
<nav>
<a href="Login.html"> Login </a> |
<a href="Signup.html">SignUp</a> |
<a href="TrackOrder.html"> Track order </a>
</nav>
<h1>Welcome to Ekart's Shopping</h1>
<nav>
<a href="#Clothing"> Clothing </a> |
<a href="#Media"> Media </a>
</nav>
</header>
<article>
Ekart& Co very own one-stop solution for all your shopping needs !<br/>
Dont believe us? Click on the offers and check it out for yourself !!

<h2 id="Clothing"> Clothing </h2>


<imgsrc="#.jpg" alt="Image" width="350" height="250"><br><br>

<h2 id="Media"> Media </h2>


Listen to some music: <br/>
<audio src="music.mp3" controls ="controls"></audio><br/><br>
<br/>
View Video: <br/>
<video src="seaView.mp4" controls="controls" width="350" height="250"></video>
</article>
<footer>
<nav>
About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions
</nav>
Copyright &copy; 2018 | Giri
</footer>
<aside>
Like and Connect with us FB Twitter g+
</aside>
</body>
</html>
Mean Full Stack Lab Manual
Output:

Experinment-3a:
Aim:
Write a JavaScript program to find the area of a circle using radius (var and let - reassign and observe
the difference with var and let) and PI (const)

Description:

In JavaScript, there are three types of identifiers, variables, functions, and labels. Variable identifiers are used to
name variables, function identifiers are used to name functions, and label identifiers are used to label statements.
Identifiers must follow certain naming conventions, such as starting with a letter or underscore, and can contain
letters, numbers, and underscores.
Source Code:

<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="Online, Shopping" />
<title>JavaScript</title>
</head>
<body>
<script>
let radius=10;
var rad=10;
const pi =3.14;
document.write(pi*(rad**2));
document.write("<br>");
var rad=20;
document.write(pi*(rad**2));
document.write("<br>");

</script>
Mean Full Stack Lab Manual
</body>
</html>

Output:

Experinment-3b:
Aim:
Write JavaScript code to display the movie details such as movie name, starring, language, and
ratings. Initialize the variables with values of appropriate types. Use template literals wherever necessary.
Description:

Primitive data types are the building blocks of data and include undefined, null, Boolean, number, and string. They
are called "primitive" because they are immutable and have a fixed size in memory.

Non-primitive data types include objects and arrays, and are also known as reference types. These data types can
be of any size and can be changed dynamically. They are called "reference" types because they are not stored
directly
Source Code:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script>
let movie={
name:"RRR",
starring:5,
language:"Telugu",
ratting: 9.8,
};
for(key in movie){
document.write(key + " : ");
document.write(movie[key]);
document.write("<br>");
};
</script>
</body>
</html>
Output:
Mean Full Stack Lab Manual

Experinment-3c:
Aim:
Write JavaScript code to book movie tickets online and calculate the total price, considering the
number of tickets and price per ticket as Rs. 150. Also, apply a festive season discount of 10% and calculate
the discounted amount.
Description:
Operators are symbols used in JavaScript to perform operations on values or variables. There are different types
of operators in JavaScript such as arithmetic operators, assignment operators, comparison operators, logical
operators, bitwise operators, and more

Source Code:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h4>Your Ticket Details:</h4>
<br>
<script>
let x= Number(prompt("Enter No. of tickets : "));
document.write("Total no. of seats Books : "+x);
document.write("<br>");
document.write("Cost of "+x+" tickets : " +(150*x));
document.write("<br>");
document.write("Festival Season Discount : 10%");
document.write("<br>");
document.write("Total cost after discount is : "+((x*150)-(x*(10/100)*150)));
</script>
</body>
</html>
Mean Full Stack Lab Manual
Output:

Experinment-3d:
Aim:
Write a JavaScript code to book movie tickets online and calculate the total price based on the 3
conditions: (a) If seats to be booked are not more than 2, the cost per ticket remains Rs. 150. (b) If seats are 6
or more, booking is not allowed. (c) If else.
Description:

In JavaScript, there are two main types of statements: non-conditional statements and conditional statements. Non-
conditional statements are executed in a sequential order, whereas conditional statements allow us to execute code based
on a certain condition. The two main types of conditional statements are "if" statements and "switch" statements. "If"
statements are used to execute a block of code if a specified condition is true, while "switch" statements are used to
perform different actions based on different conditions

Source Code:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h4>Your Ticket Details:</h4>
<br>
<script>
let i=0;
let y=[3,5,7,9,11];
let x=prompt("No of Tickets?");
x=Number(x);
if(x<=2){
document.getElementById("11").innerHTML="Tickets booked <br>"+"Cost for "+x+" Tickets is "+
((x*150));
}
else if(x>=6){

document.getElementById("11").innerHTML="Booking is not allowed";


}
else{
document.write("Tickets booked <br>"+"Cost for "+x+" Tickets is "+((x*150)-(x*(y[x-
1]/100)*150)));
Mean Full Stack Lab Manual
}
</script>
</body>
</html>

Output:

Experinment-3e:
Aim:

Write a JavaScript code to do online booking of theatre tickets and calculate the total price based on the below
conditions:

1. If seats to be booked are not more than 2, the cost per ticket remains rs 150.
2. If seats are 6 or more, booking is not allowed.
3. If seats to be booked are more than 2 but less than 5, based on the number of seats booked, do the
following:
 Calculate total cost by applying a discount of 5, 7, 9, 11 percent, and so on for customer
1,2,3 till 5.
 Try the code with different values for the number of seats.

Implement the problem statement using 'for' loop, 'while' loop and 'do-while' loop.

Description:

In JavaScript, loops are used to execute a set of statements repeatedly until a certain condition is met. There are
three types of loops in JavaScript: for loop: This loop executes a block of code for a specified number of times.
for (initialization; condition; increment/decrement) while loop: This loop executes a block of code as long as the
condition is TRUE

do-while loop: This loop executes a block of code once before checking the condition. If the condition is true, the
loop will repeat
Source Code:

<!DOCTYPE html>
<html>
<head>
<title>Booking Details</title>
</head>
<body>
<script>
Mean Full Stack Lab Manual
let x=prompt("No of Tickets?");
x=Number(x);
let i=0;
let y=5;
let total=0;
document.write("<b>Your ticket Details:</b><br>")
for(i=0;i<x;i++){
document.write("Ticket for Customer "+(i+1)+" gets "+y+"% discount! , cost is : " +((150)-
((y/100)*150))+"<br>");
total+=((150)-(x*(y/100)*150))
y+=2
}
document.write("for "+x+" tickets You need to pay : "+total+" instead of "+(x*150)+" <br>")
</script>
</body>
</html>

Output:

Experinment-4a:
Aim:

Write a JavaScript code to do online booking of theatre tickets and calculate the total price based on the below
conditions:

1. If seats to be booked are not more than 2, the cost per ticket remains 150rs.
2. If seats are 6 or more, booking is not allowed.
3. If seats to be booked are more than 2 but less than 5, based on the number of seats booked, do the
following:
 Calculate total cost by applying a discount of 5, 7, 9, 11 percent, and so on for customer 1,2,3
till 5.
 Try the code with different values for the number of seats.

Write the following custom functions to implement given requirements:

1. calculateCost(seats): Calculate and display the total cost to be paid by the customer for the tickets
they have bought.
2. calculateDiscount(seats): Calculate discount on the tickets bought by the customer. Implement using
arrow functions.

Description:

Functions are reusable blocks of code that perform a specific task. In JavaScript, there are several types of
functions, including
Mean Full Stack Lab Manual

Named Functions: These functions are defined using the function keyword, followed by the function name, and a
pair of parentheses. They can be invoked by calling their name

Anonymous Functions. These functions are defined without a name, and are often used an callbacks or event
listeners.

Arrow Functions Introduced in ES6, arrow functions are a shorthand way of writing anonymous functions

Function Parameters Functions can accept one or more parameters, which act as inputs to the function

Nested Functions: Functions can be defined inside other functions, creating a hierarchy of functions

Built-in Functions: JavaScript comes with several built-in function, such as parseInt(), parseFloat(), and
Math.random().

Variable Scope in Functions: Variables declared inside a function have local scope, and are not accessible
outside of the function, Variables declared outside of a function have global scope, and can be accessed anywhere
in the code,

To declare a function in JavaScript, use the function keyword, followed by the function name and a pair of
parentheses. The code inside the function is enclosed in curly braces. To invoke the function, simply call its
name, optionally passing in any required parameters.

Source Code:

<!DOCTYPE html>
<html>
<head>
<title>Booking Details</title>
</head>
<body>
<script>
let x=prompt("No of Tickets?");
let total=0;
x=Number(x);
document.write("<b>Your ticket Details:</b><br>");
document.write("Actual cost per ticker is : 150 <br>")
if(x>2 && x<6){
document.write("Seats are available <br>");
let i=0;
let y=5;
for(i=0;i<x;i++){
document.write("Ticket for Customer "+(i+1)+" gets "+y+"% discount! , cost is : " +((150)-
((y/100)*150))+"<br>");
total+=((150)-(x*(y/100)*150));
y+=2;
};

}
else{
document.write("Seats are not available <br>");
};
document.write("for "+x+" tickets You need to pay : "+total+" <br>");
Mean Full Stack Lab Manual

</script>
</body>
</html>
Output:

Experinment-4b:
Aim:
Create an employee class extending from a base class Person. Hints: (i) Create a class Person with
name and age as attributes. (ii) Add a constructor to initialize the values (iii) Create a class Employee
extending Person with additional attributes role
Description:

Working with classes in JavaScript involves creating and using objects that have a defined set of properties and
behaviors. Classes are used to define the structure and behavior of objects, and can be created and instantiated
using the class keyword.

Classes in JavaScript can also inherit properties and methods from other classes, which is known as inheritance.
Inheritance allows classes to reuse code and build on existing functionality, which can lead to more efficient and
organized code.

To create a class, the class keyword is used, followed by the name of the class and a set of curly braces. Properties
and methods are defined within the class using constructor functions and prototype methods.
To inherit from a class, the extends keyword is used to specify the class being inherited from. Inherited properties
and methods can be accessed using the super keyword

Source Code:

<!DOCTYPE html>
<html>
<head>
<title>Booking Details</title>
</head>
<body>
<script>
class Person{
constructor(name,age){
this.name=name;
Mean Full Stack Lab Manual
this.age=age;
}
}
class Employee extends Person{
constructor(name,age,role,salary){

super(name,age);
this.role=role;
this.salary=salary;
}
Details(){
document.write("<b>Employee Details:</b><br>");
document.write("Name: "+this.name+"<br>");
document.write("Age: "+this.age+"<br>");
document.write("Role: "+this.role+"<br>");
document.write("Salaty: "+this.salary+"<br>");
}
}
let c=new Employee("Chakri","20","Software Developer","1,00,000");
c.Details();

</script>
</body>
</html>
Output:

Experinment-4c:
Aim:

Write a JavaScript code to make online booking of theatre tickets and calculate the total price based on the
below conditions:

1. If seats to be booked are not more than 2, the cost per ticket remains 150.
2. If seats are 6 or more, booking is not allowed.
3. If seats to be booked are more than 2 but less than 5, based on the number of seats booked, do the
following:
 Calculate total cost by applying a discount of 5, 7, 9, 11 percent, and so on for customer
1,2,3 till 5.
 Try the code with different values for the number of seats.
Mean Full Stack Lab Manual

Description:

In-built events are predefined actions or occurrences that can be triggered by user actions or system events such
as clicks, mouse movements, keypresses, and form submissions. Handlers are functions that are executed in
response to events.

JavaScript provides several in-built event handlers such as onclick, onmouseover, onkeydown, onchange, and
many more that can be used to perform actions on web pages when certain events occur. These event handlers
can be used to make web pages more interactive and userfriendly by providing dynamic behavior to web
elements
Source Code:

<!DOCTYPE html>
<html>
<head>
<title>Booking Details</title>
</head>
<body>
<p><b>Your ticket Details:</b></p>
<p>Actual cost per tickets is : 150 </p>
<p id="1"></p>
<div><p id="2">click here for discount :<a onclick="toggle()" href="#">Apply</a></p></div>
<script>
let x=prompt("No of Tickets?");
let total=0;
x=Number(x);
let c=x*150;
c=String(c)
document.getElementById("1").innerHTML="Total cost :"+c;
function toggle(){
if(x>2 && x<6){
let i=0;
let y=5;
for(i=0;i<x;i++){
total+=((150)-(x*(y/100)*150));
y+=2;

};
alert("Total amount after discout : "+total);
}
else{
alert("Seats are not available");
};
}

</script>
Mean Full Stack Lab Manual
</body>
</html>

Output:
Mean Full Stack Lab Manual
Experinment-4d:
Aim:
If a user clicks on the given link, they should see an empty cone, a different heading, and a different message
and a different background color. If user clicks again, they should see a re-filled cone, a different heading, a
different message, and a differ
Description:
Working with Objects:
Objects are one of the fundamental concepts in JavaScript, and they are used to store and manipulate data. There
are several types of objects in JavaScript, including built-in objects, custom objects, and host objects.
Types of Objects:
Built-in Objects: These are the objects that are built into the JavaScript language, such as Array. Date, Math, and
RegExp.
Custom Objects: These are the objects that you create in your JavaScript code.
Host Objects: These are the objects that are provided by the browser or environment in which your JavaScript
code is running, such as window, document, and XMLHttpRequest

Source Code:

<!DOCTYPE html>
<html>
<head>
<title>DOM API for HTML modification</title>
</head>
<body style="background-color:lightblue;text-align:center">
<h1 id="hdr1">Here's your ice cream</h1>
<img id="img1" src="ice.jpg" alt="Ice cream is not ready">
<p id="p1" onclick="eat()">Click here to eat</p>
<script>
function eat(){
let x=document.getElementById("hdr1").innerHTML;
if(x=="Here's your ice cream"){
x=document.getElementById("hdr1").innerHTML="Hope you Liked it!";
document.getElementById("img1").src="ice1.jpg";
x=document.getElementById("p1").innerHTML="Click to re-fill";
}
else if(x=="Hope you Liked it!"){
x=document.getElementById("hdr1").innerHTML="Here's re-filled ice cream";
document.getElementById("img1").src="ice.jpg";
x=document.getElementById("p1").innerHTML="Click here to eat";
}
else{
x=document.getElementById("hdr1").innerHTML="Hope you Liked it!";
document.getElementById("img1").src="ice1.jpg";
x=document.getElementById("p1").innerHTML="Click to re-fill";
}
}
</script>
</body>
Mean Full Stack Lab Manual
</html>

Output:

Experinment-5a:
Aim:
Create an array of objects having movie details. The object should include the movie name, starring,
language, and ratings. Render the details of movies on the page using the array.
Description:

Creating Arrays: Arrays can be created in JavaScript by enclosing a comma-separated list of values in square
brackets []. An array can contain any type of data, ficluding numbers, strings, objects, or other arrays.

Destructuring Arrays: Array destructuring is a feature in JavaScript that allows you to unpack values from an
array into separate variables. You can use destructuring to assign array values to variables with a more concise
syntax

Array Methods: JavaScript provides a number of built-in methods for working with arrays. Some of the most
commonly used methods include
Mean Full Stack Lab Manual
push(): Adds one or more elements to the end of an array

pop(): Removes the last element from an array and returns it.

shift(): Removes the first element from an array and returns it.

unshift(). Adds one or more elements to the beginning of an array.

concat(): Joins two or more arrays together

slice(): Returns a portion of an array as a new array.

Source Code:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script>
let movie={
name:"RRR",
starring:5,
language:"Telugu",
ratting: 9.8,
};
for(key in movie){
document.write(key + " : ");
document.write(movie[key]);
document.write("<br>");
};
</script>
</body>
</html>

Output:

Experinment-5b:
Aim:

Simulate a periodic stock price change and display on the console. Hints: (i) Create a method which returns a
random number - use Math.random, floor and other methods to return a rounded value. (ii) Invoke the method
for every three seconds and stop when
Mean Full Stack Lab Manual
Description:
Introduction to Asynchronous Programming. Asynchronous programming is a programming paradigm that
allows multiple tasks to run concurrently. This means that a program can perform multiple tasks simultaneously
without blocking the execution of other tasks. In JavaScript, asynchronous programming is essential for handling
long-running operations, such as network requests or file operations, without freezing the user interface
Callbacks: A callback is a function that is passed as an argument to another function and is executed after some
operation is completed, In JavaScript, callbacks are often used in asynchronous programming to handle the
results of asynchronous operations. For example, when making a network request, a callback function can be
used to handle the response once it is received.
Promises A promise is an object that represents the eventual completion or failure of an asynchronous operation
and its resulting value. A promise has three states: pending, fulfilled, or rejected. Promises are used to handle
asynchronous operations in a more readable and maintainable way than callbacks. Promises provide a chainable
syntax that allows you to handle the result of an asynchronous operation without nesting callbacks.
Async and Await: Async/await is a newer syntax introduced in ES2017 that allows you to write asynchronous
code that looks synchronous. It is built on top of promises and provides a simpler and more concise way to handle
asynchronous operations. Async functions always return a promise, and the await keyword can be used to wait
for the resolution of a promise.
Executing Network Requests using Fetch API: The Fetch API is a modern API for making network requests in
JavaScript. It provides a simple and concise way to make HTTP requests and handle their responses. The Fetch
API returns a promise that resolves to a response object. The response object contains information about the
response, such as the status code and headers You can then use the methods provided by the response object to
extract the data from the response, such as text, JSON, or binary data
Source Code:

<!DOCTYPE html>
<html>
<head>
<title>DOM API for HTML modification</title>
</head>
<body>
<h4>Stock prices :</h4>
<p>SENSEX <p id="dem"></p></p>
<script>
let max=-1000,min=1000;
function stock(){
let marke=Math.floor((Math.random()*199)-99);
if(60000+((marke/100)*60000)>60000){
max=marke;
document.getElementById("dem").style.color="green";
}
else if(60000+((marke/100)*60000)<60000){
min=marke;
document.getElementById("dem").style.color="red";
}
document.getElementById("dem").innerHTML=60000+((marke/100)*60000);
}
setInterval(stock,3000);
</script>
</body>
</html>

Output:
Mean Full Stack Lab Manual

Experinment-5c:
Aim:
Validate the user by creating a login module. Hints: (i) Create a file login.js with a User class. (ii) Create a
validate method with username and password as arguments. (iii) If the username and password are equal
it will return "Login Successful" else w
Description:
In JavaScript, you can create a module by defining an object or function in a separate file and exporting it using
the export keyword. You can then import the module into another file using the import keyword.
Consuming modules means using the exported functions, objects, or variables from the module in other parts of
the program. To consume a module, you need to import it into the file where you want to use it and then use the
imported functions or objects as needed

Source Code:
Mean Full Stack Lab Manual
<!DOCTYPE html>
<html>
<head>
<title>Login Validation</title>
<style>
body{
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div id="logform">
<div class="di">
<div class="lab">Username</div>
<div><input type="text" class="txt" placeholder="Username" maxlength="30" id="i"></div>
</div>
<div class="di">
<div class="lab">Password</div>
<div><input type="password" class="txt" placeholder="Password" maxlength="16" id="2"></div>
</div>
<div>
<a href="#">Forget Password?</a>
</div>
<button onclick="vali()">Login</button>
<div class="di">Don't have an account? <a onclick="register()" href="#">Signup Now</a></div>
</div>
<script>
function vali(){
let user=document.getElementById("i").value;
let pass=document.getElementById("2").value;
let c=new User(user,pass);
}

class User{
constructor(user,pass){
this.user=user;
this.pass=pass;
if(this.user.length<6 || this.pass.length<8){
alert("please verify the Password & Username");
}
else{
if(this.user=="Chakri" &&this.pass=="12345678"){
alert("Login Successful");
};
};
}
}
</script>
</body>
Mean Full Stack Lab Manual
</html>

Output:

Experinment-6a:
Aim:
Verify how to execute different functions successfully in the Node.js platform.

Description:
Node.js is an open-source, cross-platform, server-side JavaScript runtime environment that allows developers to
build scalable and efficient web applications. Here are the basic steps to use Node.js:

Install Node.js on your computer by downloading the installer from the official Node.js website Create a new
project directory for your Node.js application.

Initialize the project by running the npm init command in the terminal. This will create a package.json file for
your project, which will contain the project's metadata and dependencies.

Install the required packages and dependencies for your project by running the npm install command in the
terminal. This will install the packages listed in the dependencies section of the package.json file.
Mean Full Stack Lab Manual
Write the code for your Node.js application using a code editor or IDE.

Run the application by typing node <filename>.js in the terminal, where <filename> is the name of the main file
for your application.

Step 1: Create a file demo.js in the folder created earlier.

function tester() {
alert("Hello! I am an alert box!");
}
tester();

Step 2: Run the code and observe the output.


Step 3: Modify the code as shown below:

function tester() {
var message;
if (confirm("Press a button!"))
{
message = "You pressed OK!";
} else {
message = "You pressed Cancel!";
}
console.log(message);
}
tester();
Step 5: Run the code and observe the output.

Experinment-6b:
Aim:
Write a program to show the workflow of JavaScript code executable by creating web server in Node.js.
Description:

To create a web server in Node js, you can follow these steps:

1. Open your preferred code editor and create a new file with a .js extension. Give it a meaningful name,
such as server.js.

2. Require the built-in http module at the top of your file: const http = require('http');

. Create a new server instance using the http.createServer() method. 3

const server-http.createServer((req, res) => {// Code to handle incoming requests));


Mean Full Stack Lab Manual

4. Inside the server instance, define how your server should handle incoming requests. For example, you
can use the res.writeHead() method to set the response header, and res.end() method to send the response
body })

const server http.createServer((req, res) { res.writeHead(200, { 'Content-Type" 'text/plain' ;


res.end('Hello, world!"); });

This code will send a 200 OK status code and the message "Hello, world!" to any client that sends a
request to the server.

5. Set the server to listen for incoming requests on a specific port using the server.listen() method const
port= 3000 ; server listen(port, 0 Rightarrow1 console.log("Server running at http://localhost:S (port)/);

This code will start the server on port 3000 and log a message to the console to confirm that the server is
running.

6. Save your file and start the server by running the following command in your terminal: node server.js

This will start your server, and it will be ready to receive incoming requests.

Note that this is a very basic example of how to create a web server in Node.js, and there are many other
modules and libraries you can use to create more advanced servers with features such as routing,
middleware, and database integration.
Source Code:
File name: 21mh5a4204.js

const http = require("http");


var server=http.createServer((req,res)=>{
res.write("Hello World! I have created my first server!");
res.end();
});
server.listen(3000);
console.log("Server started... Running on localhost:3000");

OUTPUT:

After running the program and navigating to http://localhost:3000/ in your web browser, you should see the
message "Hello, world!" displayed in your browser window.
Mean Full Stack Lab Manual

Experinment-6c:
Aim:
Write a Node.js module to show the workflow of Modularization of Node application.
Description:

Modular programming is a programming paradigm in which software is composed of separate, reusable


modules that can be combined to create complex applications. In Node.js, modular
programming is particularly important due to the nature of JavaScript as an asynchronous, event- driven
language.

Node.js makes it easy to create modular programs by providing a built-in module object that can be used to
define and export modules. To define a module in Node.js, you simply create a new JavaScript file and define
one or more functions or objects that you want to export using the module.exports object.
Source Code:

File: DBModule.js

exports.authenticateUser = (username, password) => {


if (username === "admin" && password ===
"admin") { return "Valid User";
}
else return "Invalid User";
};

File: 21mh5a4204.js

const http = require("http");


var dbmodule = require("./DBModule");
var server = http.createServer((request, response)
=> { result = dbmodule.authenticateUser("admin",
"admin");
response.writeHead(200, { "Content-Type": "text/html" });
response.end("<html><body><h1>" + result +
"</h1></body></html>"); console.log("Request received");
});
server.listen(3000);

console.log("Server is running at port 3000");


Mean Full Stack Lab Manual

Output:

Experinment-6d:

AIM:
Write a program to show the workflow of restarting a Node application

DESCRIPTION:
There are several ways to restart a Node.js application, depending on the circumstances.
If you are running your Node application using the node command in your terminal, you can simply stop the
current instance of the application by pressing ctrl+ c and then start a new instance by running the node command
again.

If you are running your Node application as a daemon or service, you can typically use a command-line tool
provided by your operating system to restart the service. For example, on Linux systems, you can use the systemctl
command to manage services

PROGRAM:

program that demonstrates how to restart a Node.js application using the pm2 process manager:

const http = require('http');

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


res.statusCode= 200 ;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, world!');
});
Mean Full Stack Lab Manual

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

process.on('SIGTERM', ()=>{
console.log('Received SIGTERM, shutting down gracefully');
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});

process.on('SIGINT', ()=>{
console.log(`received SIGINT, shutting down gracefully`);
server.close(() => {
console.log('Server closed');
process.exit(0);
})
})

In this program, we create a simple HTTP server that listens on port 3000 and returns a "Hello, world!" message
when a request is received. We also define two event listeners for the SIGTERM and SIGINT signals, which are
sent when the process is terminated or interrupted, respectively.

To use pm2 to manage our Node.js process, we need to install it globally using npm:

Command 1:
npm install-g pm2

Once pm2 is installed, we can start our Node.js application using the following command:
Command2 :
pm2 start app.js -name my-app
Mean Full Stack Lab Manual

This will start the application as a background process and give it the name "my-app". We can then use the
following command to view information about the process:
Command 3:
pm2 info my-app

If we need to restart the application for any reason, we can use the following command:
Mean Full Stack Lab Manual

Command 4:
pm2 restart my-app

This will gracefully shut down the current instance of the application and start a new instance in its place. If the
application crashes or encounters an error, pm2 will automatically restart it to keep it running.

OUTPUT OF ABOVE

The output of the program above will be:

Javascript code
Server running at http://localhost:3000/
This indicates that the HTTP server has started and is listening for incoming requests on port 3000.

If you want to test the HTTP server, you can open a web browser and navigate to http://localhost:3000/, or you can
use a tool like curl to make a request from the command line:

curl http://localhost:3000/
This should return the message "Hello, world!".
If you need to restart the Node.js application using pm2, you can use the following command:

code
pm2 restart my-app

This will gracefully shut down the current instance of the application and start a new instance in its place. You
should see output in the console indicating that the application has restarted:

code
[PM2] Restarting app... [PM2] App [my-app] restarted

Once the application has restarted, you can test it again to ensure that it is working correctly.

Experinment-6c:
Mean Full Stack Lab Manual

Aim:
Create a text file sre.txt and add the following data to it. Mongo, Express, Angular, Node.

DESCRIPTION:

In Node.js, file operations refer to any operation that involves reading from or writing to files on the file system.
Some common file operations include

 Reading from a file: This involves opening a file, reading its contents, and then closing the file This can
be useful for loading configuration files or reading data from a database.

 Writing to a file. This involves opening a file, writing data to it, and then closing the file. This can be
useful for logging data or saving user input to a file

 Appending to a file: This involves opening a file in "append mode", which allows you to add new data to
the end of the file without overwriting any existing data

 Deleting a file: This involves deleting a file from the file system. This can be useful for cleaning up
temporary files or removing files that are no longer needed.

Node.js provides several built-in modules for performing file operations, including the fs module, which provides a
simple and consistent API for working with files. With the fs module, you can perform operations like reading,
writing, appending, and deleting files, as well as creating and renaming directories

It's important to note that file operations can be synchronous or asynchronous. Synchronous file operations block
the execution of the program until the operation is complete, while asynchronous file operations allow the program
to continue executing while the operation is in progress. Asynchronous file operations are generally preferred in
Node.js, as they can help improve the performance and responsiveness of the program

To create a text file called sre.txt and add the data "Mongo, Express, Angular, Node" to it, you can use the
following steps:

1 Create a new folder for your project, if one does not already exist
2. Open a text editor such as Notepad, or a code editor like VSCode.
3. In the text editor, type the following text.
code

Mongo. Express, Angular, Node

4 Save the file with the name sre.txt and make sure to select "All Files" as the file type.
5. Move the src.txt file to the folder for your project.
You have now created a text file called sre.txt and added the data "Mongo, Express, Angular. Node" to it.

The output of the above process would be a text file named sre.txt containing the text "Mongo, Express, Angular,
Node"
Mean Full Stack Lab Manual
You can verify that the file has been created and contains the correct text by opening the file in a text editor or
using a command in the terminal or command prompt to view the contents of the file. For example, in Windows
Command Prompt, you can use the command type sre.txt to view the contents of the file in the command prompt

Output:

Experinment-7a:

AIM
Implement routing for the Adventure Trails application by embedding the necessary code in the routes/route.js file.

DESCRIPTION:
Defining a route
To define a route in an Express, js application, use the METHOD(path bandier) function. where METHOD is the
HTTP method (such as GET or POST), path is the URL path for the route, and handler is the function that will be
called when the route is accessed.

Handling routes
When a request is made to a defined route, the corresponding handler function will be called. The handler function
takes two parameters: req (the request object) and res (the response object).

PROGRAM
File name :router.js
const express = require('express');
const router = express.Router();
const Trail = require('./trails');

// Get all trails


router.get('/trails', (req, res) => {
Trail.find({}, (err, trails) => {
if (err) {
console.error(err);
res.status(500).send('Error retrieving trails');
} else {
res.json(trails);;
Mean Full Stack Lab Manual
}
});
});

// Add a new trail


router.post('/trails', (req, res) => {
const newTrail = new Trail({
name: req.body.name,
location: req.body.location,
difficulty: req.body.difficulty,
length: req.body.length
});

newTrail.save((err, trail) => {


if (err) {
console.error(err);
res.status(500).send('Error adding trail');
} else {
res.json(trail);;
}
});
});

// Update an existing trail


router.put('/trails/:id', (req, res) => {
Trail.findByIdAndUpdate(req.params.id, req.body, { new: true }, (err, trail) => {
if (err) {
console.error(err);
res.status(500).send('Error updating trail');
} else if (!trail) {
res.status(404).send('Trail not found');
} else {
res.json(trail);;
}
});
});

// Delete an existing trail


router.delete('/trails/:id', (req, res) => {
Trail.findByIdAndDelete(req.params.id, (err, trail) => {
if (err) {
console.error(err);
res.status(500).send('Error deleting trail');
} else if (!trail) {
Mean Full Stack Lab Manual
res.status(404).send('Trail not found');
} else {
res.json(trail);;
}
});
});

module.exports=router;

File name: trail.js


const mongoose = require('mongoose');

const trailSchema = new mongoose.Schema({


name: String,
location: String,
difficulty: String,
length: Number
});

const Trail = mongoose.model('Trail', trailSchema);

module.exports = Trail;

Note that we are using the Trail model from the models/trail.js file to interact with the database. Also, we are
using the body-parser middleware to parse incoming request bodies, so make sure to include the following line
in your main app.js file:
app. use (express.json());
This allows us to access the request body as a JavaScript object in our route handlers.

OUTPUT:

id": "60e34e8aa522c0246c5cf6fa",

"name": "Hiking Trail",

"location": "Mountain Range",

"difficulty": "Intermediate",

"length": "5 miles",


Mean Full Stack Lab Manual

"_v":0
},

"_id": "60e34f0a82b19017c2a35611",

"name": "Biking Trail".

"location": "Coastal Region".

"difficulty": "Advanced",

"length”: "10 miles”,

“- v “ :0

}]

Experinment-7b:

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

DESCRIPTION:
Middleware is a function that can be executed before the final request handler is called. It can intercept the
request, perform some operation on it, and pass it on to the next middleware or to the final request handler.

When a middleware is called, it receives three arguments; req, res, and next. req represents the request object,
res represents the response object, and next is a function that is called to pass control to the next middleware in the
stack

Middleware functions can be used to perform various operations, such as logging, authentication, error
handling, and data validation. They can also modify the request or response objects, add new properties or methods
to them, or terminate the request-response cycle by sending a response.

Middleware functions can be chained together using the next function. When a middleware calls next(), it
passes control to the next middleware in the stack. If next() is not called, the request will be stuck in the current
middleware and the response will not be sent.

PROGRAM:
Mean Full Stack Lab Manual

const express = require('express');


const app = express();
const notes = [ ]; // Assuming you have a global array to store notes here

// Middleware for parsing JSON body of POST requests


app.use(express.json());

// Middleware for handling POST submissions


app.post('/notes', (req, res, next) => {
// Get the note from the request body
const note = req.body;

// Validate the note


if (!note.title || !note.body) {
// If the note is invalid, send a customized error message
return res.status(400).send('Title and body are required.');
} else {
// If the note is valid, log it and pass control to the next middleware
console.log('New note:', note);
next();
}
});

// Route handler for displaying all notes


app.get('/notes', (req, res) => {
// Display all notes
res.send(notes);
});

// Route handler for displaying a single note by ID


app.get('/notes/:id', (req, res) => {
// Find the note by ID
const note = notes.find((note) => note.id === parseInt(req.params.id));

// If the note is found, display it


if (note) {
res.send(note);
} else {
// If the note is not found, send a customized error message
res.status(404).send('Note not found.');
}
});
Mean Full Stack Lab Manual
// Start the server
const port = 3000; // You can change the port as needed
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

In the above code, we first use the built-in express json() middleware to parse the JSON body of POST
requests. Then we define a middleware function to handle POST submissions. This middleware function
first extracts the note object from the request body and then validates it. If the note is invalid, it sends a
customized error message to the client. If the note is valid, it logs it to the console and passes control to the
next middleware

We then define route handlers for displaying all notes and a single note by ID. In the handler for
displaying a single note, we first find the note by ID and then check if it exists. If the note is found, we
send it to the client. If the note is not found, we send a customized error message to the client

By using middleware functions, we can modularize our code and separate concerns, making it easier to
maintain and debug.

OUTPUT:
A specific output for the myNotes application without knowing the complete code of the application. However,
the output of the code snippet I provided in the previous message would be as follows:

When a POST request is made to /notes with a valid JSON body, the note object would be logged to the console
and the response status would be set to 200 with no response body.

When a POST request is made to notes with an invalid JSON body, the response status would be set to 400 and
the response body would be the string "Title and body are required."

When a GET request is made to notes, the response body would be an array of all the notes in the notes array.

When a GET request is made to /notes/ad with a valid ID, the response body would be the note object with the
matching ID.

When a GET request is made to /notes/:id with an invalid ID, the response status would be set to 404 and the
response body would be the string "Note not found."
Mean Full Stack Lab Manual

Experinment-7c:

AIM:
Write a Mongoose schema to connect with MongoDB.

DESCRIPTION:
First install mongoose by entering command : npm install mongoose
Connecting to MongoDB with Mongoose: Mongoose is an Object Data Modeling (ODM) library for MongoDB
and it provides a simple way to connect to a MongoDB database using Mongoose.connect() method. To
establish a connection, you need to pass the database URL and options (if any) as parameters to the
Mongoose.connect() method.

Validation Types: Mongoose provides a set of built-in validators that can be used to validate data before it is
saved to the database. These validators include required, min, max, enum, match, and more. To use a validator,
you need to define it as a property of the schema field

Defaults: Mongoose also allows you to set default values for fields in a schema. You can define a default value
for a field by setting the default property of the field.

PROGRAM:

file name :app.js


const express = require('express');
const mongoose = require('mongoose');
const app = express();

// Connect to MongoDB database using mongoose


mongoose.connect('mongodb://localhost:27017/mynotes2')
.then(() => console.log('Connected to MongoDB database'))
.catch(err => console.error('Error connecting to MongoDB database:', err));

// Define the Note schema


const noteSchema = new mongoose.Schema({
title: {
Mean Full Stack Lab Manual
type: String,
required: true,
},
body: {
type: String,
required: true,
},
createdOn: {
type: Date,
default: Date.now
},
updatedOn: {
type: Date,
default: Date.now
}
});

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

// create new note


const newNote = new Note({
title: 'my first note',
body: 'this is the body of my first note'
});
newNote.save()
.then(note => console.log("Note is created successfully",note))
.catch(err => console.error(err));

// read all notes


Note.find()
.then(notes => console.log('All notes:', notes))
.catch(err => console.error(err));

// read single note by ID


Note.findById('603dc404bf62f4a4d91a92af')
.then(note => console.log('Note found by id:', note))
.catch(err => console.error(err));

// update a note by ID
Note.updateOne({ _id: '603dc404bf62f4a4d91a92af' }, { title: 'Updated title'})
.then(result => console.log('Note updated successfully:', result))
.catch(err => console.error(err));

// delete a note by ID
Mean Full Stack Lab Manual
Note.deleteOne({ _id: '603dc404bf62f4a4d91a92af' })
.then(result => console.log('Note deleted successfully:', result))
.catch(err => console.error(err));

// start the server


const Port = 3000;
app.listen(Port, () => {
console.log(`Server started on port ${Port}`);
});

OUTPUT:

This code connects to a MongoDB database using Mongoose, defines the Note schema, and performs various
operations on the Note model using Mongoose methods such as .save(), find(), findById(), updateOne(), and
deleteOne(). The output of the code will depend on the specific operations being performed and the state of the
MongoDB database.

Experinment-7b:

AIM:

Write a program to wrap the Schema into a Model object.

DESCRIPTION:

In the context of an Express application, models are typically used to represent data and define the interactions
with a database. A model typically corresponds to a database table and is responsible for defining the schema and
providing methods for interacting with the data.

PROGRAM:

const mongoose= require('mongoose');

//Define the schema


const userSchema= new mongoose.Schema({
name: {
type: String,
required:true,
},
age:{
type: Number,
default: 18,
},
Mean Full Stack Lab Manual
email :{
type: String,
required: true,
unique: true,
match: /^\S+@\S+\.\S+$/,

},
});

//create the model object


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

//Using the Model to Interact with Database:


//With the User model, you can perform CRUD operations (Create, Read, Update, Delete) on the user
collection in your MongoDB database.

Output :

The output of the program will depend on the specific database operations being performed. Here's an example of
the output you might see when running a program that retrieves all users from the database using the find()
method of the User model object:

User.find()
.then(notes => console.log('All notes:', notes))
.catch(err => console.error(err));

Assuming there are three users in the database, the output might look something like this:

[
{ _id: '609ed60b70c0f9384409e8a6', name: 'John Doe', age: 30, email: [email protected]'},
{_id: '609ed60b70c0f9384409e8a7', name: 'Jane Smith', age: 25, email: [email protected]'},
{ _id: '609ed60b70c019384409e8a8', name: 'Bob Johnson', age: 40, email: [email protected]'}
]

This output shows an array of three user objects, each with an ID, name, age, and email.
Mean Full Stack Lab Manual

Experinment-8a:

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

DESCRIPTION:

CRUD (Create, Read, Update, Delete) operations are common operations used in web development. In
Express.js, we can perform CRUD operations using HTTP methods like GET. POST, PUT, and DELETE.

PROGRAM:

const mongoose = require('mongoose');

// Connect to MongoDB database using mongoose


mongoose.connect('mongodb://localhost:27017/User', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('Connected to MongoDB database'))
.catch(err => console.error('Error connecting to MongoDB database:', err));

// Define the User schema


const userSchema = new mongoose.Schema({
Name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
});

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

// Asynchronous function to perform database operations


async function performDatabaseOperations() {
try {
// Create new user
const newUserdata = new Userdata({
Name: 'Reddy',
email: '[email protected]',
Mean Full Stack Lab Manual
});
await newUserdata.save();

// Read all users


const users = await Userdata.find();
console.log('All users:', users);

// Read single user by ID


const userById = await Userdata.findById('603dc404bf62f4a4d91a92af');
console.log('User found by ID:', userById);

// Update a user by ID
const updatedUser = await Userdata.updateOne({ _id: '603dc404bf62f4a4d91a92af' }, { Name: 'Updated
Name' });
console.log('User updated successfully:', updatedUser);

// Delete a user by ID
const deletedUser = await Userdata.deleteOne({ _id: '603dc404bf62f4a4d91a92af' });
console.log('User deleted successfully:', deletedUser);
} catch (error) {
console.error(error);
}
}

// Call the function to perform database operations


performDatabaseOperations();

Output:
Mean Full Stack Lab Manual
Experinment-8b :

AIM:
In the myNotes application, include APIs based on the requirements provided. (1) API should fetch the details of
the notes based on a notesID which is provided in the URL.. Test URL-http://1ocalhost:3000/notes/ 75555(iii)
API should update the details

DESCRIPTION:

API development in Express.js involves creating API endpoints that can handle incoming HTTP requests, process
them, and send back appropriate responses. The API endpoints can be used by clients to access and manipulate
data or perform other operations.

PROGRAM:

Filename : app.js

const express=require('express');
const mongoose=require('mongoose');
const Note=require('./note');

const app = express();

// Connect to MongoDB database


mongoose.connect('mongodb://localhost/myNotes');

// Endpoint to fetch a note by its ID


// Express route handler to fetch a note by its ID
app.get('/notes/:id', async (req, res) => {
try {
const id = req.params.id;
const isValidObjectId = mongoose.Types.ObjectId.isValid(id);
if (!isValidObjectId) {
return res.status(400).json({ message: 'Invalid ObjectId' });
}
const note = await Note.findById(id);
if (!note) {
return res.status(404).json({ message: 'Note not found' });
}
res.json(note);
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Internal server error' });
}
Mean Full Stack Lab Manual
});

// Start the server


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

Filename: note.js

// Import the mongoose library


const mongoose = require('mongoose');

// Define the schema for the Note model


const noteSchema = new mongoose.Schema({
title: String,
content: String
});

// Create the Note model using the schema


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

// Export the Note model


module.exports = Note;

OUTPUT :
run app.js by using command node app.js
As this code is meant to be run on a server, there won't be any visible output on the console. However, we can
test the API using a tool like Postman or a web browser.

Assuming that the API is running on localhost:3000, we can send a GET request to the endpoint /notes/:id by
visiting the URL http://localhost:3000/notes/:id in a web browser or using Postman.

If a note with ID 7555 exists in the database, its details will be returned as a JSON response. For example:
{
"id":"6159078f7b9ca2d3fcf3b2c8",
"title": "Shopping list",
"content": "Milk, eggs, bread, cheese",
}
If a note with ID :id doesn't exist in the database, a 404 status code will be returned along with a message. For
example

{"message": "Note not found" }


Mean Full Stack Lab Manual

Experinment-8c:

Aim:
Write a program to explain session management using cookies.

DESCRIPTION:
Session management and cookies are important concepts in web development for maintaining user state and
improving user experience.

Sessions are used to maintain user state across multiple requests. When a user logs in to a website, a session is
created on the server, and a unique session ID is generated and stored in a cookie on the user's browser. This
session ID is used to identify the user's session on subsequent

requests, allowing the server to retrieve session data and maintain user state. Sessions can be used to store user-
specific data such as user ID, username, user preferences, etc.

Cookies are small text files that are stored on the user's browser. They are used to store user- specific data such as
login credentials, user preferences, and session IDs. Cookies can be set by the server or by client-side scripts, and
they are sent to the server with each request. Cookies can also be used to store information about the user's activity
on the website, such as the pages they have visited, the items they have added to their cart, etc.

Together, sessions and cookies enable web applications to maintain user state, personalize the user experience, and
provide a more seamless user experience,

Install cookies parser before excuting the code


npm install express express-session cookie-parser

PROGRAM:
File name: app.js

const express = require('express');


const session = require('express-session');
const cookieParser = require('cookie-parser');

const app = express();


const port = 3000;
Mean Full Stack Lab Manual
// Set up middleware for session and cookie parsing
app.use(cookieParser());
app.use(session({
secret: 'mysecretkey',
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}));

// Middleware to parse JSON bodies


app.use(express.json());

// Middleware to parse URL-encoded bodies


app.use(express.urlencoded({ extended: true }));

// Set up a simple login page


app.get('/', (req, res) => {
res.send(`
<h1>Login</h1>
<form method="post" action="/login">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>
<button type="submit">Submit</button>
</form>
`);
});

// Handle login form submission


app.post('/login', (req, res) => {
const { username, password } = req.body;

// Check if the username and password are valid


if (username === 'admin' && password === 'password') {
// Set a session cookie with the user's ID
req.session.userId = 1;
res.send('<p>Login successful!</p>');
} else {
res.send('<p>Invalid username or password.</p>');
}
});

// Display a welcome message if the user is logged in


Mean Full Stack Lab Manual
app.get('/welcome', (req, res) => {
const userId = req.session.userId;
if (userId) {
res.send(`<p>Welcome, user ${userId}!</p>`);
} else {
res.send('<p>Please log in to view this page.</p>');
}
});

// Log out the user by destroying the session


app.get('/logout', (req, res) => {
req.session.destroy();
res.send('<p>You have been logged out.</p>');
});

// Start the server


app.listen(port, () => {
console.log(`Server running on port ${port}`);
});

Output:
Run this command node app.js

Username :admin
Password: password
After entering the username and password see the changes in cookies session
Mean Full Stack Lab Manual

Enter wrong username and password see the output

Experinment-8d:

AIM:
Write a program to explain session management using sessions.

DESCRIPTION:
In web development, a session is a way to store and persist user data across multiple requests from the same user.
Sessions allow a web application to keep track of user state and information, such as login credentials, shopping
cart contents, and user preferences

When a user logs in or interacts with a web application, the server creates a unique session for that user, which is
associated with a session ID. The session ID is then stored as a cookie in the user's browser, and the server can
use it to retrieve the corresponding session data for that user on subsequent requests
Install session library’s using this command
npm install express express-session
PROGRAM:

Filename : app.js
Mean Full Stack Lab Manual
const express = require('express');
const session = require('express-session');
const app = express();

app.use(session({
secret: 'mysecretkey',
resave: false,
saveUninitialized: true
}));

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


const sessionData = req.session;
if (sessionData.views) {
sessionData.views++;
res.setHeader("Content-Type", "text/html");
res.write(`<p>Number of views: ${sessionData.views}</p>`);
res.write(`<p>Session ID: ${sessionData.id}</p>`);
res.write(`<p><a href="/logout">Logout</a></p>`);
res.end();
} else {
sessionData.views = 1;
res.send("Welcome to the session demo! Refresh the page to increase the view count.");
}
});

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


req.session.destroy((err) => {
if (err) {
console.log(err);
} else {
res.redirect('/');
}
});
});

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

Output :
To Run use : node app.js
Server started on port 3000
Enter URL in browser: http:localhost:3000
Mean Full Stack Lab Manual

When we refresh the page , we see the view count increase :

Experinment-8e:

AIM:
Implement security features in myNotes application

DESCRIPTION:
Security is a critical concern for any web application, and it is essential to ensure that the application is protected
against common web vulnerabilities such as cross-site scripting (XSS), cross-site request forgery (CSRF), and
other attacks. In addition, it is important to ensure that sensitive user data is encrypted in transit and at rest, and
that the application is protected against attacks like SQL injection.

One of the ways to enhance the security of an Express.js application is by using middleware. Middleware
functions are functions that have access to the request and response objects, and can modify them or perform
other actions based on the needs of the application.

Helmet is a collection of middleware functions that help to improve the security of an Express.js application.
Mean Full Stack Lab Manual
Helmet includes middleware functions that set various HTTP headers that can help protect against attacks such as
XSS and CSRF, as well as middleware that helps to secure cookies and enable HTTP Strict Transport Security
(HSTS).

PROGRAM:

1 Authentication: Implement a user authentication system to ensure that only authorized users can access and
modify their notes. This can be done using third-party authentication services like OAuth or by creating a custom
authentication system.

Here's an example of a custom authentication system using Passport.js middleware:

const passport = require('passport');


const LocalStrategy = require('passport-local').Strategy;
const User = require('/models/user');

passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));

app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/notes');
}
);

2. Authorization: Once the user is authenticated, implement an authorization system to ensure that users can only
access and modify their own notes. This can be done using role-based access control or by associating notes with
specific users in the database.

Here's an example of associating notes with specific users in MongoDB:


const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const noteSchema = new Schema({


title: String,
body: String,
Mean Full Stack Lab Manual
user: { type: Schema.Types.ObjectId, ref: 'User' }
});

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

module.exports = Note;

3. Encryption: Ensure that user data is encrypted both in transit and at rest. This can be done using SSL/TLS
encryption for in-transit data and data encryption at the database level.

Here's an example of enabling SSL / TLS encryption in an Express.js application:


const https = require('https');
const fs = require('fs');

const privateKey = fs.readFileSync('key.pem', 'utf8');


const certificate = fs.readFileSync('cert.pem', 'utf8');

const credentials = { key: privateKey, cert: certificate };


const app = require('express');
const httpsServer = https.createServer(credentials, app);

httpsServer.listen(443, () => {
console.log('HTTPS Server running on port 443');
});

4. Helmet middleware: Finally, use the Helmet middleware to implement additional security measures like setting
various HTTP headers to protect against attacks such as XSS and CSRF.

Here's an example of using the Helmet middleware in an Express.js application:

const express = require('express');


const helmet = require('helmet');
const app = express();
app.use(helmet());
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Mean Full Stack Lab Manual

Experinment-9a:
Aim:
On the page, display the price of the mobile-based in three different colors. Instead of using the number in our
code, represent them by string values like GoldPlatinum, PinkGold, SilverTitanium.

DESCRIPTION:
TypeScript is a statically-typed superset of JavaScript that is designed to help developers write more robust
and maintainable code. It adds optional type annotations and other language features to JavaScript, making it
easier to catch errors at compile-time rather than at runtime.

TypeScript is developed and maintained by Microsoft and is open-source. It can be used to build large-scale
applications in both client-side and server-side environments. TypeScript code is transpired into JavaScript
code, which can then be run on any browser or server that supports JavaScript

Install typescript use this command :

npm install -g typescript

File: product.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">

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

}
Mean Full Stack Lab Manual
.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">

<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="glyphicon glyphicon-shopping-cart"


style="color:white"></span></a></li>

</ul>
Mean Full Stack Lab Manual
</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;">

<img src="SamsungGalaxy_Gold.jpg" height="250px">

</div>

<div style="padding-top:10px;">

<div style="cursor:pointer;color:Steelblue;text-align: center;"><b>

<span id="pName"></span></b></div>

<div style="padding-top:10px;padding-left: 101px;">

<b>Price:</b>&nbsp;&dollar;<span id="pPrice"></span>

</div>

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

</div>

</div>

</div>

</div>

</body>

<!--Adding the converted js file -->

<script src="productlist.js"></script>

</html>

File: productlist.ts

let mobileName: string = "Samsung Galaxy Note 7";


let pPrice: string = "2,100";
let pAvailable: string = "Available";

document.getElementById("pName")!.innerHTML = mobileName;
document.getElementById("pPrice")!.innerHTML = pPrice;
Mean Full Stack Lab Manual
document.getElementById("pAvailable")!.innerHTML = pAvailable;

Output:
First Compile : tsc Filename.ts

Experinment-9b:
Aim:
Define an arrow function inside the event handler to filter the product array with the selected product object
using the productId received by the function. Pass the selected product object to the next screen.
Description:

In TypeScript, functions are first-class citizens, which means that they can be treated like any other value or
variable. This allows for greater flexibility and expressiveness when defining functions in TypeScript.

To define a function in TypeScript, you use the function keyword, followed by the function name and a set of
parentheses that contain any parameters that the function takes. The function body us then enclosed in curly braces,
and the return type is specified after the closing parenthesis of the parameter list, using a colon followed
by the return type

Source code :

<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;
Mean Full Stack Lab Manual
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">
<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="glyphicon glyphicon-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;">
<img src="SamsungGalaxy_Gold.jpg"height="250px">
</div>
<div style="padding-top:10px;">

<div onclick="getMobileDetails('Samsung',432);"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>
<div style="padding-left: 100px;"><b>Status:</b><span id="pAvailable0"></span></div>

</div>
Mean Full Stack Lab Manual

</div>
<div class="col-md-4">
<div style="text-align: center;">
<img src="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;">
<img src="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>
</html>

File: arrays.ts

const productlist: any[] = [


{ pId: 432, productName: "Samsung Galaxy Note 7", productPrice: 699, productAvailable: true, imageUrl:
"SamsungGalaxy_Gold.jpg", productDescription: "Samsung Galaxy Note 7 is a stylish mobile you can ever have.
It has 64GB memory." },
{ pId: 231, productName: "Samsung Galaxy s6 Edge", productPrice: 630, productAvailable: true, imageUrl:
"samsung_edge_silver.jpg", productDescription: "Samsung Galaxy s6 Edge is a stylish mobile you can ever have.
It has 64GB memory." },
{ pId: 875, productName: "Nokia Lumina 640XL", productPrice: 244, productAvailable: false, imageUrl:
"lumia_640xl.jpg", productDescription: "Nokia Lumina 640XL is a stylish mobile you can ever have. It has 64GB
memory." },
];

for (let i = 0; i < productlist.length; i++) {


document.getElementById(`pName${i}`)!.innerHTML = productlist[i].productName;
document.getElementById(`pPrice${i}`)!.innerHTML = productlist[i].productPrice;

if (productlist[i].productAvailable) {
document.getElementById(`pAvailable${i}`)!.innerHTML = "Available";
Mean Full Stack Lab Manual
} else {
document.getElementById(`pAvailable${i}`)!.innerHTML = "Unavailable";
}
}

// Define an event handler function to get mobile details


function getMobileDetails(productName:String,productId: number): void {
const selectedProduct = productlist.find(product => product.pId == productId);
if (selectedProduct) {
alert(selectedProduct.productDescription);
// You can further pass the selectedProduct to the next screen or perform other actions here
} else {
alert("Product not found");
}
}

Output :

Experinment-9c:
Aim:
Consider that developer needs to declare a function - getMobileByVendor which accepts string as input
parameter and returns the list of mobiles.

Source code :
// declaring a function which accepts string datatype as parameter and returns string array

function getMobileByManufacturer(manufacturer: string): string[] {

let mobileList: string[];


Mean Full Stack Lab Manual
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;

// logic to populate the Samsung manufacturer details on console

console.log('The available mobile list: ' + getMobileByManufacturer('Samsung'));

Output:

Experinment-9d:
Aim:
Consider that developer needs to declare a manufacturer's array holding 4 objects with id and price as a
parameter and needs to implement an arrow function - my function to populate the id parameter of
manufacturers array whose price is greater than or equal.

Source Code:
// declaring an Array with 3 objects

const manufacturers = [

{ id:'Samsung', price:150 },

{ id:'Microsoft', price:200 },

{ id:'Apple', price:400 },

{ id:'Micromax', price:100 }
Mean Full Stack Lab Manual
];

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

Output:

Experinment-9e:
Aim:
Declare a function - getMobileByManufacturer with two parameters namely manufacturer and id, where
manufacturer value should passed as Samsung and id parameter should be optional while invoking the
function, if id is passed as 101 then this function
Source Code:

// declaring a function with optional parameter


function getMobileByManufacturer(manufacturer: string = 'Samsung', id?: number): string[] {
let mobileList: string[];
// logic to be evaluated if id parameter while invoking above declared function
Mean Full Stack Lab Manual
if (id) {
if (id === 101) {
mobileList = ['Moto G Play, 4th Gen', 'Moto Z Play with Style Mod'];
return mobileList;
}
}
// logic to return mobileList based on manufacturer category
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;
}
}
// statement to invoke function with optional parameter
console.log('The available mobile list : ' + getMobileByManufacturer('Apple'));
// statement to invoke function with default parameter
console.log('The available mobile list : ' + getMobileByManufacturer(undefined, 101));

Output:

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

Source Code:

const cart: string[] = [];


const pushtoCart = (item: string) => { cart.push(item); };
function addtoCart(...productName: string[]): string[] {
for (const item of productName)
{
pushtoCart(item);
}
return cart;

}
Mean Full Stack Lab Manual
console.log('Cart Items are:' + addtoCart(' Moto G Play, 4th Gen', ' Apple iPhone 5s'));

Output:

Experinment-10b:
Aim:
Declare an interface named - Product with two properties like productId and productName with a number and
string datatype and need to implement logic to populate the Product details.
Description:

Source code:

interface Product {
productId: number ;
productName: string ;
}
function getProductDetails(productobj: Product): string {
return'The product name is : ' + productobj.productName;
}
const prodObject = {productId:1001, productName:'Mobile'};
const productDetails: string = getProductDetails(prodObject);
console.log(productDetails);

Output:

Experinment-10c:
Aim:
Declare an interface named - Product with two properties like productId and productName with the number
and string datatype and need to implement logic to populate the Product details.
Mean Full Stack Lab Manual

Source code:

interface Product {
productId: number;
productName: string;
}
function getProductDetails(productobj: Product): string {
return 'The product name is : ' + productobj.productName;
}
const prodObject1 = {
productId:1001,
productName:'Mobile',
productCategory:'Gadget'
};
const productDetails1:string = getProductDetails(prodObject1);
console.log(productDetails1);

Output:

Experinment-10d:
Aim:
Declare an interface with function type and access its value.

Source code:
function CreateCustomerID(name: string, id: number): string { return'The customer id is ' + name + ' ' + id;
}
interface StringGenerator {
(chars: string, nums: number): string;
}
let idGenerator: StringGenerator; idGenerator = CreateCustomerID;
const customerId: string = idGenerator('Mr.Tom', 101); console.log(customerId);
Output:
Mean Full Stack Lab Manual

Experinment-11a:
Aim:
Declare a product List interface which extends properties from two other declared interfaces
like Category, Product as well as implementation to create a variable of this 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 extends from Category and Product interfaces
interface ProductList extends Category, Product {
list: Array<string>;
}

// Declaring a variable which is of type 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);
Mean Full Stack Lab Manual

Output:

Experinment-11b:
Aim:
Consider the Mobile Cart application, Create objects of the Product class and place them into the productlist
array.

Source Code:

// 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';
}
return 'Product Name is Mobile';
}
getGadget(): string[] {
return ['Mobile', 'Tablet', 'iPad', 'iPod'];
}
}
// creating instance of class of interface type
const gadget: Product = new Gadget();
Mean Full Stack Lab Manual
// creating variable to hold return value of displayProductName function
const productName: string = gadget.displayProductName(101);
// line to populate Product name on console
console.log(productName);

Output :

Experinment-11c:
Aim:
Declare a class named - Product with the below-mentioned declarations: (i) productId as number property (ii)
Constructor to initialize this value (iii) getProductId method to return the message "Product id is <id va>".

Source Code:

class Product3 {
productId:number;
constructor(productId:number) {
this.productId=productId;
}

getroductId() {

return `Product Id is ${this.productId}`;


}
}

const product=new Product3(123);


console.log(product.getroductId());

Output:
Mean Full Stack Lab Manual
Experinment-11d:

Aim:
Create a Product class with 4 properties namely productId, productName, productPrice, productCategory with
private, public, static, and protected access modifiers and accessing them through Gadget class and its
methods.
Description:

Source Code:

class Product1 {

private productId:number;
public productName:string;
protected productPrice:number;
static productCategory:string='Electronics';

constructor(productId:number, productName:string, productPrice:number) {


this.productId = productId;
this.productName = productName;
this.productPrice = productPrice;
}

getProductDetails(){
return `Product ${this.productName}(id:${this.productId}, price:${this.productPrice})`
}
}

class Gadget {
constructor(private product:Product1) {}
getProductCategory(){
return Product1.productCategory;
}

getProductDetails(){
return this.product.getProductDetails()
}
}

const product2=new Product1(123,"samsung",1500);


const gadget1=new Gadget(product2);

console.log(gadget1.getProductCategory());
Mean Full Stack Lab Manual
console.log(gadget1.getProductDetails());

Output:

Experinment-12a:
Aim:
Create a Product class with 4 properties namely productId and methods to setProductId() and getProductId().

Source Code:

class Product2 {
private productId:number ;
constructor(productId:number) {
this.setProductId(productId)
}
setProductId(productId:number) {
this.productId = productId
}
getProductId() {
return this.productId;
}
}

const product3=new Product2(123);


console.log(product3.getProductId());
product3.setProductId(456);
console.log(product3.getProductId());

Output :

Experinment-12b:
Mean Full Stack Lab Manual
Aim:
Create a namespace called ProductUtility and place the Product class definition in it. Import the Product class
inside productlist file and use it.
Description:

Step 1: Create a file namespace_demo.ts

namespace Utility {
export namespace Payment {
export function CalculateAmount(price: number, quantity: number): number {
return price * quantity;
}
}

export function MaxDiscountAllowed(noOfProduct: number): number {


if (noOfProduct > 5) {
return 40;
} else {
return 10;
}
}

function privateFunc(): void {


console.log('This is private...');
}
}

Step 2: Create another file Namespace_import.ts

/// <referencepath="./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);
console.log(`Maximum discount allowed is: ${discount}`);

Step 3: Open Node.js command prompt, change directory to the folder in which Namespace file

resides and run the below command from the command line

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


Mean Full Stack Lab Manual

Experinment-12c:
Aim:
Consider the Mobile Cart application which is designed as part of the functions in a module to calculate the
total price of the product using the quantity and price values and assign it to a totalPrice variable.
Description:

Step 1: Create a file module_demo.ts


export function MaxDiscountAllowed(noOfProduct: number): number {
if (noOfProduct>5) {
return 30;
} else {
return 10;
}
}
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);
const discount = MaxDiscountAllowed(2);
console.log(`Maximum discount allowed is: ${discount}`);
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 the below
command from the command line
Mean Full Stack Lab Manual

Step 4: Run node 2.module_import.js from the command line

Experinment-12d:
Aim:
Create a generic array and function to sort numbers as well as string values.

Source Code:

function sortedArr<T>(arg: Array<T>): Array<T> {

const sortedArray: Array<T> = arg.sort((n1, n2) => {

if (n1 > n2) { return 1; }

if (n1 < n2) { return -1; }

return 0;

});

return sortedArray;

const num: Array<number> = [5, 12, 23, 42, 34];

const str: Array<string> = ['C', 'F', 'V', 'A'];

const sortedNum = sortedArr(num);

console.log(sortedNum);

const sortedStr = sortedArr(str);

console.log(sortedStr);

const stringArray: string[] = ['G', 'Z', 'A', 'D'];

const sortedStringArray = sortedArr(stringArray);

console.log(sortedStringArray);
Mean Full Stack Lab Manual
Output:

You might also like