Mean Stack Technologies Lab Record
Mean Stack Technologies Lab Record
pg. 1
HTML5 - The Language
Exercise - 1a:
Module name:
Problem Statement:
Homepage.html:
<!DOCTYPE html>
<html>
<head>
<title>Hussain's Shopping</title>
</head>
<body>
</body>
</html>
Output:
pg. 2
HTML5 - The Language
Problem Statement:
Consider the below code for Homepage.html. Enhance the semantics of content by adding
appropriate sectioning elements to achieve the below-mentioned expected output.
Homepage.html:
<!DOCTYPE html>
<html>
<head>
<title>Hussian's Shopping</title>
<meta name="keywords" content="Online, Shopping" />
</head>
<body>
Login | SignUp | Track order Welcome to Hussian's Shopping Clothing | Media
Hussain's very own one-stop solution for all your shopping needs !
Dont believe us? Click on the offers and check it out for yourself !! Clothing Media About
Us | Privacy Policy |Contact Us | FAQ | Terms & Conditions Copyright 2018 | Giri Like and
Connect with us
FB Twitter g+
</body>
</html>
Output:
pg. 3
HTML5 - The Language
Exercise – 1c:
Module na me: Paragraph Element, Division and Span Elements, List Element
Make use of appropriate grouping elements such as list items to "About Us" page of IEKart's
Shopping Application
Problem statement:
Enhance the semantics of content by adding appropriate grouping elements such as list items in the
below-given code.
Aboutus.html:
<!DOCTYPE html>
<html>
<head>
<title>Hussian's Shopping</title>
<meta name="keywords" content="Online, Shopping" />
</head>
<body>
<header>
<nav> Login | SignUp | Track order </nav>
<h1> Welcome to Hussian's Shopping </h1>
<nav> Electronics | Books | Sports | Media | Clothing | Offers Zone
</nav>
</header>
<article>
<h2>About Us</h2> Hussain's 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 | Giri
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>
</html>
pg. 4
Output:
Problem statement:
Enhance semantics of content by adding the Link elements in the below-given code
Homepage.html.
Links to be added:
1.Link "Login", "SignUp" and "Track order" to "Login.html", "SignUp.html" and "Track.html" page
respectively.
Homepage.html
<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="Online, Shopping" />
<title>Hussain's Shopping</title>
</head>
<body>
<header>
pg. 5
<nav> Login | SignUp | Track order </nav>
<h1>Welcome to Hussain's Shopping</h1>
<nav> Clothing | Electronics </nav>
</header>
<article>
Hussain's one-stop solution for all your shopping needs ! Dont believe us? Click on the offers and
check it out for yourself !! <h2 id="Clothing"> Clothing </h2>
<h2 id="Electronics"> Electronics</h2>
</article>
<footer>
<nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav> Copyright
2016 | ETA UI and MarkUp
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>
</html>
Output:
Problem statement:
pg. 6
Consider below the Home page of Hussain's Shopping application. Modify the below code and
add the © symbol in the footer.
Homepage.html
<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="Online, Shopping" />
<title>Hussain's 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 Hussain's Shopping</h1>
<nav>
<a href="#Clothing"> Clothing </a> | <a href="#Media"> Media </a>
</nav>
</header>
<article> Hussain & 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:
pg. 7
HTML5 - The Language
Exercise – 1f:
Module name:
HTML5 Global Attribute Add the global attributes such as contenteditable, spellcheck, id etc. to
enhance the Signup Page functionality of IEKart's Shopping application.
Problem statement:
Consider the Signup Page of Hussain's Shopping application. Enhance its functionality by adding
global attributes such as contenteditable and spellcheck to populate the below-given output.
Signup.html
<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="Online, Shopping" />
<title>Hussain's 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 /></td>
</tr>
<tr>
pg. 8
<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 /></td>
</tr>
<tr>
<td><label for="gender">Gender:</label></td>
<td><label for="male">Male<input type="radio" id="male" name="gender" value="M"
/> <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>
<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>
pg. 9
<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
© 2018 | Giri
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>
</html>
Output:
pg. 10
HTML5 - The Language
Exercise – 2a:
Module name:
Enhance the details page of IEKart's Shopping application by adding a table element to display the
available mobile/any inventories.
Problem statement:
Consider the Details page of Hussain's Shopping application. Enhance its functionality by adding a table
element to display the available mobile inventories to populate the below- given output.
Details.html
<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="Online, Shopping" />
<title>Hussain's Shopping</title>
</head>
<body>
<table border="1">
<caption>Mobile Inventories Available at Hussain's Shopping!</caption>
<!-- Design the table here -->
</table>
</body>
</html>
Output:
pg. 11
Exercise – 2b:
Module name: Creating Form Elements, Color and Date Pickers, Select and Datalist Elements
Using the form elements create Signup page for IEKart's Shopping application.
Problem statement:
Signup.html
<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="Online, Shopping" />
<title>Hussian's Shopping</title>
</head>
<body>
<header>
<h1>Sign Up!</h1>
</header>
<article>
<!-- Add form here-->
<br /> <br /> <br /> <br />
</article>
<footer>
<nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav> Copyright
© 2018 | Giri
</footer>
<aside> Like and Connect with us FB Twitter g+ </aside>
</body>
</html>
pg. 12
3. Javascript
a) Type of Identifiers
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)
Program:
var radiusVar = 5;
let radiusLet = 7;
const PI = 3.14159;
// Reassign radiusLet
radiusLet = 10;
output:
Program:
pg. 13
function applyDiscount(totalPrice, discountPercentage) {
return totalPrice - (totalPrice * discountPercentage);
}
// Display results
console.log(`Number of Tickets: ${numTickets}`);
console.log(`Price per Ticket: Rs. ${pricePerTicket}`);
console.log(`Total Price without Discount: Rs. ${totalPriceWithoutDiscount}`);
console.log(`Festive Season Discount (${festiveSeasonDiscount * 100}%): Rs. $
{totalPriceWithoutDiscount - discountedAmount}`);
console.log(`Total Price after Discount: Rs. ${discountedAmount}`);
output:
Number of Tickets: 5
Price per Ticket: Rs. 150
Total Price without Discount: Rs. 750
Festive Season Discount (10%): Rs. 75
Total Price after Discount: Rs. 675
Program:
pg. 14
// Function to book movie tickets
function bookTickets(numTickets) {
if (numTickets <= 0) {
return "Please enter a valid number of tickets to book.";
} else if (numTickets <= 2) {
return calculateTotalPrice(numTickets, pricePerTicket);
} else if (numTickets > maxSeatsAllowed) {
return "Booking not allowed. Maximum seats allowed for booking is 5.";
} else {
return "Booking not allowed for the given number of tickets.";
}
}
// Example usage
const numTicketsToBook = 3; // Example: Booking 3 tickets
const totalPrice = bookTickets(numTicketsToBook);
// Display result
console.log(`Number of Tickets to Book: ${numTicketsToBook}`);
console.log(`Total Price: Rs. ${totalPrice}`);
// Display result
console.log(`Number of Tickets to Book: ${numTicketsToBook1}`);
console.log(`Total Price: Rs. ${totalPrice1}`);
output:
pg. 15
4. Javascript
Program:
// Example usage:
const person1 = new Person("John", 30);
console.log("Person:", person1);
Output:
pg. 16
b) Working with Objects, Types of Objects, Creating Objects, Combining and cloning
Objects using Spread operator, Destructuring Objects, Browser Object Model, Document
Object Model
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
Program:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Click to See Cone</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="container">
<h1 id="heading">Click to See Cone</h1>
<p id="message">Click the button to reveal the cone!</p>
<button id="revealButton" onclick="toggleCone()">Reveal Cone</button>
<div id="cone"></div>
</div>
<script src="script.js"></script>
</body>
</html>
Styles.css:
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
#container {
text-align: center;
margin-top: 50px;
}
#cone {
width: 200px;
height: 200px;
border-radius: 50%;
border: 2px solid #333;
background-color: transparent;
margin: 20px auto;
}
pg. 17
.hidden {
display: none;
}
.filled {
background-color: #ffc107;
}
Script.js:
function toggleCone() {
const cone = document.getElementById('cone');
const heading = document.getElementById('heading');
const message = document.getElementById('message');
isConeFilled = !isConeFilled;
}
pg. 18
5. Javascript
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
Program:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Movies</title>
</head>
<body>
<div id="moviesContainer"></div>
<script src="script.js"></script>
</body>
</html>
JavaScript (script.js):
pg. 19
// Add more movie objects as needed
];
movies.forEach(movie => {
const movieDiv = document.createElement("div");
movieDiv.innerHTML = `
<h2>${movie.name}</h2>
<p><strong>Starring:</strong> ${movie.starring.join(", ")}</p>
<p><strong>Language:</strong> ${movie.language}</p>
<p><strong>Ratings:</strong></p>
<ul>
<li>IMDb: ${movie.ratings.IMDb}</li>
<li>Rotten Tomatoes: ${movie.ratings.RottenTomatoes}</li>
<li>Metacritic: ${movie.ratings.Metacritic}</li>
</ul>
`;
moviesContainer.appendChild(movieDiv);
});
}
output:
pg. 20
b) Introduction to Asynchronous Programming, Callbacks, Promises, Async and Await,
Executing Network Requests using Fetch API
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
Program:
function generateRandomPriceChange() {
const priceChange = Math.floor(Math.random() * 11) - 5;
return priceChange;
}
output:
pg. 21
Stock Price Change: 1 New Price: 97
Stock Price Change: 0 New Price: 97
Stock Price Change: 2 New Price: 99
Stock Price Change: 3 New Price: 102
Simulation stopped after 30 seconds.
Program:
login.js
class User {
constructor(username, password) {
this.username = username;
this.password = password;
}
validate(username, password) {
if (username === this.username && password === this.password) {
return "Login Successful";
} else {
return "Invalid username or password";
}
}
}
module.exports = User;
main.js
Output:
Login Successful
pg. 22
6. Node.js
To execute different functions successfully in the Node.js platform, you typically follow these steps:
Install Node.js: First, ensure you have Node.js installed on your system. You can download and
install it from the official website: Node.js Download.
Create a JavaScript file: Create a .js file where you will write your Node.js code. You can use any
text editor or an Integrated Development Environment (IDE) for this purpose.
Write your functions: Define your functions within the JavaScript file. Here's an example:
myFunctions.js
function add(a, b) {
return a + b;
}
Export functions: If you want to use these functions in another file, you need to export them. In Node.js,
you can use module.exports or exports object for this purpose. For example:
myFunctions.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = {
add,
subtract
};
Import functions (optional): If you want to use these functions in another file, you need to import them
using require. For example:
pg. 23
index.js
Run your file: To execute your Node.js script, open your terminal or command prompt, navigate to the
directory containing your JavaScript file, and run node filename.js, replacing filename.js with the name of
your JavaScript file.
node index.js
Program:
// Import required modules
const http = require('http');
To run this program, save it in a file (e.g., server.js) and execute it using Node.js:
pg. 24
node server.js
math.js
app.js
To run this application, ensure that math.js and app.js are in the same directory, and execute app.js using
Node.js:
node app.js
Output:
Result of addition: 8
Result of subtraction: 2
pg. 25
Here's how you can set up a simple Node.js application with nodemon:
Install nodemon: First, install nodemon globally on your system using npm:
npm install -g nodemon
Create your Node.js application: Create a simple Node.js application. For this example, let's create a file
named app.js:
app.js
Run the application with nodemon: Instead of running your Node.js application directly, you'll
run it with nodemon:
Test the application: Visit http://127.0.0.1:3000/ in your web browser, and you should see "Hello,
World!" displayed.
Modify the application: Now, let's make a change to our application. For example, change the
text to "Hello, Nodemon!" in the app.js file.
Observe automatic restart: Once you save the changes, nodemon will detect the file change and
automatically restart your Node.js application. You'll see the console output indicating that the
server has restarted.
e) File Operations
Create a text file src.txt and add the following data to it. Mongo, Express, Angular, Node.
const fs = require('fs');
// File path
const filePath = 'src.txt';
pg. 26
console.log('Data has been written to src.txt');
}
});
7. Express.js
pg. 27
a) Defining a route, Handling Routes, Route Parameters, Query Parameters
// routes/routes.js
// Define routes
router.get('/', (req, res) => {
res.send('Welcome to AdventureTrails!');
});
// Import routes
const routes = require('./routes/routes');
// Use routes
app.use('/', routes);
pg. 28
In myNotes application: (i) we want to handle POST submissions. (ii) display customized
error messages. (iii) perform logging.
app.use(middleware1);
app.use(middleware2);
app.use(middleware3);
pg. 29
Write a Mongoose schema to connect with MongoDB
// Import Mongoose
const mongoose = require('mongoose');
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myDatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
}).catch((err) => {
console.error('Error connecting to MongoDB:', err);
});
pg. 30
d) Models
Write a program to wrap the Schema into a Model object.
// Import Mongoose
const mongoose = require('mongoose');
// Example usage
const myCar = new Car({
brand: 'Toyota',
model: 'Corolla',
year: 2020,
price: 20000
});
8. Express.js
pg. 31
a) CRUD Operations
Write a program to perform various CRUD (Create-Read-Update-Delete) operations using
Mongoose library functions.
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myDatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
}).catch((err) => {
console.error('Error connecting to MongoDB:', err);
});
pg. 32
}
});
// Update a book by ID
app.put('/books/:id', async (req, res) => {
try {
const { title, author, pages } = req.body;
const updatedBook = await Book.findByIdAndUpdate(req.params.id, { title, author, pages },
{ new: true });
if (!updatedBook) {
return res.status(404).json({ message: 'Book not found' });
}
res.json(updatedBook);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
// Delete a book by ID
app.delete('/books/:id', async (req, res) => {
try {
const deletedBook = await Book.findByIdAndDelete(req.params.id);
if (!deletedBook) {
return res.status(404).json({ message: 'Book not found' });
}
res.json({ message: 'Book deleted successfully' });
} catch (error) {
res.status(500).json({ message: error.message });
}
});
b) API Development
pg. 33
In the myNotes application, include APIs based on the requirements provided. (i) API
should fetch the details of the notes based on a notesID which is provided in the URL. Test URL -
http://localhost:3000/notes/7555 (ii) API should update the details bas
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myNotesDB', { useNewUrlParser: true,
useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Error connecting to MongoDB:', err));
pg. 34
res.json(updatedNote);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
pg. 35
app.get('/destroySession', (req, res) => {
req.session.destroy((err) => {
if (err) {
console.error('Error destroying session:', err);
res.send('Error destroying session');
} else {
res.send('Session destroyed successfully');
}
});
});
d) Sessions
Write a program to explain session management using sessions.
pg. 36
});
9. Typescript
pg. 37
a) Basics of TypeScript
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.
b) Function
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.
interface Product {
productId: number;
productName: string;
// Other properties
}
if (selectedProduct) {
// Pass the selected product object to the next screen
// Assuming you have a function to navigate to the next screen
navigateToNextScreen(selectedProduct);
} else {
console.error('Selected product not found');
}
}
pg. 38
const handleButtonClick = (productId: number) => {
handleProductSelection(productId);
};
// Example usage
const samsungMobiles = getMobileByVendor('Samsung');
console.log('Samsung Mobiles:', samsungMobiles);
d) Arrow Function
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 - myfunction
to populate the id parameter of manufacturers array whose price is greater than or equal
interface Manufacturer {
id: number;
price: number;
}
pg. 39
{ id: 4, price: 400 }
];
// Example usage
const priceThreshold = 250;
const result = myFunction(priceThreshold);
console.log(`Manufacturer IDs with price greater than or equal to ${priceThreshold}:`, result);
// Example usage
const manufacturer = 'Samsung';
const id = 101; // Optional parameter
pg. 40
a) Rest Parameter
Implement business logic for adding multiple Product values into a cart variable
which is type of string array.
// Example usage
addToCart('Product 1', 'Product 2', 'Product 3');
console.log('Cart:', cart); // Output: ['Product 1', 'Product 2', 'Product 3']
b) Creating an Interface
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.
// Example usage
const productId = 1;
const productName = 'Product 1';
pg. 41
// Populate product details
const productDetails = populateProductDetails(productId, productName);
console.log('Product Details:', productDetails);
c) Duck Typing
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.
// Example usage
const productId: number = 123;
const productName: string = 'Example Product';
d) Function Types
Declare an interface with function type and access its value.
pg. 42
// Access the value of the implemented functions
console.log('Result of addition:', add(5, 3)); // Output: 8
console.log('Result of subtraction:', subtract(8, 3)); // Output: 5
11. Typescript
pg. 43
a) Extending Interfaces
Declare a productList interface which extends properties from two other declared
interfaces like Category,Product as well as implementation to create a variable of this
interface type
// Declare the ProductList interface which extends properties from Category and Product
interface ProductList extends Category, Product {}
b) Classes
Consider the Mobile Cart application, Create objects of the Product class and place
them into the productlist array.
pg. 44
const productList: Product[] = [product1, product2, product3];
c) Constructor
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 value>>"
// Example usage
const product = new Product(123);
console.log(product.getProductId());
Output: "Product id is 123"
d) Access Modifiers
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.
pg. 45
this.productId = productId;
this.productName = productName;
this.productCategory = productCategory;
}
Output: "Smartphone"
1
“Electronics”
1000
12. Typescript
pg. 46
a) Properties and Methods
Create a Product class with 4 properties namely productId and methods to
setProductId() and getProductId().
Output: 123
pg. 47
// Method to get productId
getProductId(): number {
return this.productId;
}
}
}
Output: 123
// Example usage
const quantity = 3;
const price = 100; // Assume the price of the product is $100
Output: 300
pg. 48
d) What is Generics, What are Type Parameters, Generic Functions, Generic Constraints
Create a generic array and function to sort numbers as well as string values.
pg. 49