MSD Lab Programs
MSD Lab Programs
AIM:
Write a JavaScript to 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.
SOURCE CODE: [Link]
<!DOCTYPE html>
<html>
<head>
<title>Pan Indian Movies</title>
<style>
.mydiv {
text-decoration: bold;
text-align: left;
margin-top: 10px;
height: 200px;
width: 1450px;
border: 4px solid purple;
text-align: left;
color: red;
background-color: #c7f15e;
font-family: verdana;
font-size:20pt;
padding: 15px;
}
</style>
</head>
<body bgcolor="lightblue">
<center>
<h1 style="color:red;font-size:38pt;"><b>Render the Details of Telugu
Pan Indian Movies </b></h1>
<img src="[Link]" width="360px" height="400px" >
<img src="[Link]" width="360px" height="400px" >
<img src="[Link]" width="360px" height="400px">
<div class="mydiv">
<p id="movie-list"></p>
<script>
const movies=[
{ name: 'Kalki', starring: 'Prabhas,Deepika Padukone,Disha Patani',
director: 'Nag Ashwin', language: 'Pan India', ratings: 9.6 },
{ name: 'Devara', starring: 'Jr. N.T. R ,Janhvi Kapoor,Saif Ali Khan',
director: 'Koratala Siva',language: 'Pan India', ratings: 9.5 },
{ name: 'Pushpa2', starring: 'Allu Arjun,Rashmika,Fahadh Faasil',
director:'Sukumar',language: 'Pan India', ratings: 9.7 }
];
const movieList = [Link]('movie-list');
[Link](movie => {
const p = [Link]('p');
[Link] = `${[Link]} (${[Link]}), Starring: $
{[Link]}, Director: ${[Link]},Ratings:$
{[Link]}`;
[Link](p);
});
</script>
</center>
</div>
</body>
</html>
Exercise -2
AIM:
a).Write a JavaScript to 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
SOURCE CODE: [Link]
<!DOCTYPE html>
<html>
<head>
<title> Employee Details</title>
<style>
.mydiv {
text-decoration: bold;
text-align: left;
margin-top: 10px;
width: 700px;
height: 550px;
border: 6px solid purple;
text-align: center;
color: blue;
background-color: #c7f15e;
font-family: verdana;
font-size:25pt;
}
</style>
</head>
<body bgcolor="pink">
<center>
<h1 style="color:red;font-size:40pt;"><b>Creating and Inheriting Classes
</b></h1>
<div class="mydiv">
<script type="text/javascript">
class Person
{
constructor(name, age,empid)
{
[Link] = name;
[Link] = age;
[Link] = empid;
}
}
class Employee extends Person
{
constructor(name, age,empid,job,salary,mobileno,emailid,role)
{
super(name, age,empid);
[Link]=job;
[Link]=salary;
[Link]=mobileno;
[Link]=emailid;
[Link] = role;
}
getEmployeeDetails()
{
[Link]("<br><br>*** EMPLOYEE INFORMATION ***<br>");
[Link](" <br> Name : "+[Link]);
[Link](" <br> Age : ",[Link]);
[Link]("<br> Empid : ",[Link]);
[Link]("<br> Job : ",[Link]);
[Link]("<br> Salary : ",[Link]);
[Link]("<br>Mobile No : ",[Link]);
[Link]("<br>Email Id : ",[Link]);
[Link]("<br> Job Role : ",[Link]);
}
}
let employee1 = new Employee("Karth", 25,"Sacet180", "Software",100000,
9110307238,"Dr [Link]@[Link]","Software Manager");
[Link]();
</script>
</div>
</body>
</html>
AIM:
b).Write a JavaScript to validate the user by creating a login module. Hints:
(i) Create a file [Link] 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 will return "Unauthorized access".
SOURCE CODE: [Link]
<!DOCTYPE html>
<html>
<head>
<title>Creating a Login Module</title>
<style>
.mydiv {
text-decoration: bold;
margin-top: 10px;
width: 600px;
height:400px;
border: 5px solid purple;
text-align: center;
color: blue;
background-color: #c7f15e;
font-family: verdana;
font-size:25pt;
padding: 20px;
}
</style>
</head>
<body style="background-color:#F0E68C;">
<center>
<h1 style="color:red;font-size:35pt;">Creating a Login Module</h1>
<div class="mydiv">
<script src="[Link]">
</script>
<form id="login-form">
<br><br>
<label for="username"><b>Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password"><b>Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Login"
onclick="validate()"> <input type="reset" value="Reset">
<br><br>
<div id="result"></div>
</center>
</body>
</html>
[Link]
class User {
constructor(username, password)
{
[Link] = username;
[Link] = password;
}
validate() {
if ([Link] === [Link]) {
return "Login Successful!";
}
else {
return "Unauthorized Access!";
}
}
}
function validate() {
form = [Link]('login-form');
resultDiv = [Link]('result');
username = [Link]('username').value;
password = [Link]('password').value;
[Link]();
const user = new User(username, password);
const result = [Link]();
[Link] = result;
}
Exercise -3
a).Write a program to show the workflow of JavaScript code
executable by creating web
server in [Link].
SOURCE CODE:
const http = require("http"); // Importing the http module
var server = [Link]((req,res) => { // Creating server
[Link]( ` // Sending the response
<!DOCTYPE html>
<html>
<head>
<title>[Link] Server</title>
</head>
<body bgcolor="pink">
<br><br><center><h1><font color="blue" size="25">Hello World!
Welcome To CSE! </font></h1>
<h1><font color="red" size="20">[Link]'s College of
Engineering&Technology! </font></h1>
<h2><font color="green" size="15">This page is served by a simple
[Link] server. </font></h2>
</center></body>
</html>
`);
[Link](); // [Link]() function is used to end the response process.
});
[Link](3000); // server listening to port 3000 of your computer.
[Link]("Server started... Running on localhost:3000");
AIM:
Write a [Link] module to show the workflow of Modularization of
Node application
SOURCE CODE: [Link]
// Create your own Module
[Link] = (username, password) => {
if (username === "admin" && password === "admin") {
return "Valid User!";
} else return "Invalid User";
};
How to import the [Link] file into another file [Link]?
[Link]
const http = require("http");
var nodemodule =require("./NodeModule");
var server =[Link]((request, response) => {
result = [Link]("admin", "admin");
// The [Link]() method is the status code where 200 means it is OK,
while the second
argument is an object containing the response headers.
[Link](200, { "Content-Type": "text/html" });
[Link]( `
<!DOCTYPE html>
<html>
<head> <title>[Link] </title>
</head>
<body style="background-color:#F0E68C;">
<br><br>
<center><h1><font color="red" size="30"><u>Modular Programming
in [Link] </u> </font></h1>
<h1><font color="blue" size="25">Hello World! Welcome To
CSE!</font></h1>
<h1><font color="red" size="24">[Link]'s College of
Engineering&Technology! </font></h1>
<h2><font color="green" size="15">This page is served by a simple
[Link] server. </font></h2></center></body></html>
`);
[Link]("<center><h1>" + result +"</h1> </center>");
[Link]("Request Received");
});
[Link](2000);
[Link]("Server is running at port 2000");
Exercise -4
AIM:
Write a [Link] program to show the workflow of restarting a Node
application.
SOURCE CODE: [Link]
const http = require("http");
var server = [Link]((req, res) => {
[Link]("Hello World! I have created my first server!");
[Link]();
});
[Link](3000);
[Link]("Server started... Running on localhost:3000");
AIM:
Implement Middleware for myNotes application:
(i) we want to handle POST submissions.
(ii) display customized error messages.
(iii) perform logging.
SOURCE CODE: [Link]
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var morgan = require('morgan');
const morganBody= require( 'morgan-body');
//Simple app that will log all requests in the Apache combined format to
the file [Link].
var LogStream = [Link]([Link](__dirname,
'[Link]'), { flags: 'a' });
[Link](morgan('combined', { stream: LogStream }));
morganBody(app, {
noColors: true,
stream: LogStream,
});
[Link]((req, res,next)=> {
if(10<20) {
next();
}
});
//Handle Get Submission in [Link]
[Link]('/getRequest', (req, res)=> {
[Link](`
<!DOCTYPE html>
<html>
<head>
<title>[Link] </title>
</head>
<body style="background-color:#F0E68C;">
<br><br><br><center><h1><font color="red" size="25">Hello World!
Welcome To CSE!</font></h1>
<h1><font color="red" size="25"> Develop Middleware in
[Link]</font></h1>
<h1><font color="blue" size="24"> Handle Get Submission in
[Link]-Middleware</font></h1>
</center></body>
</html>
`);
next();
});
//Handle Post Submission in [Link]
[Link]('/postRequest', (req, res)=> {
[Link]("Handle Post Submission in [Link]-Middleware")
next();
});
[Link](function(err, req, res, next) {
// Do logging and user-friendly error message display
[Link](err);
[Link]({status:500, message: 'internal error', type:'internal'});
})
[Link](5000, () => {
[Link](`Server is running on [Link]
});
Exercise-5
AIM: Write a [Link] program to write a Mongoose schema to
connect with MongoDB
PROCEDURE STEPS:
Step1: Installing two packages express and mongoose for mongodb
database:
For installing the Mongoose library, issue the below command in
the Node command prompt.
PS D:\MSD LAB\ Exercise-4 > npm i express mongoose
Step2:Connecting to MongoDB using Mongoose(open mongoDB
database):
To establish a connection to the MongoDB database, create a
connection object using Mongoose. This is done through the below
code:
const mongoose = require('mongoose');
[Link]('mongodb://localhost:27017/Database_Name');
Step3: Create a [Link] file in VSCODE or [Link] command prompt .
Step4: Start the server using the following node command.
PS D:\MSD LAB\ Exercise-4 > node [Link] press enter button then
server starts.
Step 5: Open the postman and select the POST from the list box and
enter the URL
[Link]
Step 6: Open the Body, click on the none list box and select the raw
and select JSON from
second list box.
Step 7: Type the following code
{
“name”: “Karth”,
“email”: “stanns@[Link]”
}
Step 8: Click on the send button and click on Preview then output will
be displayed
in JSON format.
Step 9: Now, open the MongoDB database, see your database,
collection and document.
(The output data is transferred from server to client and also to
MongoDB database).
SOURCE CODE: [Link]
const express = require('express');
const mongoose = require('mongoose');
const app = express();
// Define Mongoose schema
const Schema = [Link];
const userSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
}
});
// Connect to MongoDB
[Link]('mongodb://localhost:27017/Meanstack', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
[Link]('Connected to MongoDB');
})
.catch((err) => {
[Link]('Error connecting to MongoDB:', err);
[Link](1); // Exit the application if unable to connect to
MongoDB
});
// Middleware to parse JSON bodies
[Link]([Link]());
// Create a new user document with name and email from request
body
const newUser = new User({
name: [Link],
email: [Link]
});
// Get a user by ID
[Link]('/users/:id', async (req, res) => {
try {
const user = await [Link]([Link]);
if (!user) {
return [Link](404).json({ error: 'User not found' });
}
[Link](user);
} catch (error) {
[Link]('Error fetching user:', error);
[Link](500).json({ error: 'Internal Server Error' });
}
});
// Update a user by ID
[Link]('/users/:id', async (req, res) => {
try {
const { name, email } = [Link];
const updatedUser = await
[Link]([Link], { name, email }, { new:
true });
if (!updatedUser) {
return [Link](404).json({ error: 'User not found' });
}
[Link](updatedUser);
} catch (error) {
[Link]('Error updating user:', error);
[Link](500).json({ error: 'Internal Server Error' });
}
});
// Delete a user by ID
[Link]('/users/:id', async (req, res) => {
try {
const deletedUser = await [Link]([Link]);
if (!deletedUser) {
return [Link](404).json({ error: 'User not found' });
}
[Link](deletedUser);
} catch (error) {
[Link]('Error deleting user:', error);
[Link](500).json({ error: 'Internal Server Error' });
}
});
}
}
// Gadget Class object creation
const g1: Gadget = new Gadget(180, 'SmartPhone', 'Mobile');
// invoking getProduct method with the help of Gadget object
[Link]();
// invoking getProductId method with the help of Gadget object
[Link]();
// product name property access with Gadget object
[Link]('Product Name : ' + [Link]);
namespace_import.ts
// Accessing Namespace
/// <reference path="./namespace_demo.ts" />
let paymentAmount = new [Link](180,"Apple", 2,
60500);
[Link]("Product Id :"+[Link]);
[Link]("Product Quantity : "+[Link]);
[Link]("Product Price : "+[Link]);
[Link]("Amount to be paid:"+[Link]());
Exercise -10
a) Write MongoDB queries to Create and Delete databases and collections.
CREATE OR CHANGE A DATABASE USING MONGOSH IN MONGODB:
The MongoDB Shell (mongosh) is a REPL (Read-Eval-Print
Loop) environment. It’s like a command-line interface where we can
execute MongoDB commands and interact with the database allowing us
to perform administrative tasks and read, write or manipulate data
directly.
For storing data in a MongoDB, you need to create a database first.
MongoDB has no "create" command for creating a database. you don't
need to create a database manually because MongoDB will create it
automatically when you save the value into the defined collection at first
time. You can make use of the "use" command followed by the
database_name for creating a database.
Syntax: use Database_Name
Example:
Here 'use' is the command for creating a new database in MongoDB and
‘meanstack’ is the name of the database. This will prompt you with a
message that it has switched to a new DB (database) name 'meanstack'.
For checking your currently selected database, you can use the command
db.
To see how many databases are present in your MongoDB server, write the
statement: show databases or show dbs
Method 2:
You can also create a collection during the insert process.
Syntax: [Link]({object})
Here, insertOne() function is used to store single data in the specified
collection and in the curly braces {}, we store our data .
Example,
insertMany():
To insert multiple documents at once, use the insertMany() method. This method
inserts an array of objects into the database.
Example,
>[Link]([{ name:"Sacet", course:"[Link]", branch:"CSE",
due_amt:30000, paid:"no"},{ name:"Karth", course:"[Link]", branch:"CSE",
due_amt:20000, paid:"yes"}] )
Output:
findOne(): To select only one document, we can use the findOne() method. This
method accepts a query object. This method only returns the first match it finds.
Example,
Output:
<!DOCTYPE html>
<html>
<head> <title> Registration Form</title>
<script src="[Link]
<script type="text/javascript">
function validation()
{
var name=[Link];
var pwd=[Link];
var phno=[Link];
var phlen=[Link];
var pwdlen=[Link];
var namelen=[Link];
if(namelen<6)
{
alert("The Name should be minimum 6 characters ");
if(pwdlen>6)
{
alert("Password Should not be more than 6 characters ");
if(phlen!=10)
{
alert("Phonumber Length must be 10 digits ");
}
}
}
else
alert("Registration is Successful");
}
</script>
</head>
<body bgcolor="orange">
<center>
<br><br>
<h1> <font color="red">Angular JS Form Validation & Form
Submission</font></h1>
<div ng-app = "MainApp" ng-controller="AngularController">
<form name="reg" >
<table border=1 bordercolor="green">
<tr><td>Enter Name(min 6 chars)</td><td><input type="text"
name="name" value="" ></td></tr>
<tr><td>Enter Pasword(not more than 6)</td><td><input
type="password" name="pwd" value="" ></td></tr>
<tr><td>Enter E-mail ID</td><td><input type="email" name="eid"
value="" ></td><tr>
<tr><td>Enter Phone Number(10 Digits)</td><td><input
type="number" name="phno" value="" ></td></tr>
<tr><td>Enter Date of Birth</td><td><input type="date" name="Dt"
value=""></td></tr>
<tr><td>Enter Address</td><td><textarea cols=16 name="Ta"
value="" ></textarea></td></tr>
<tr><td >    <input type="button"
value="Submit" onclick="validation()"
></td><td>    <input type="reset" ></td></tr>
</table>
</form>
</div>
</center>
</body>
</html>
b) Write a Angular program to create a new component called hello and render
Hello
Angular on the page.
Source code: [Link]
import { Component } from '@angular/core';
@Component({
selector: 'app-hello',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class HelloComponent {
courseName: string = "Angular";
}
Open [Link] file from MyApp/src folder and load the hello
component by using its selector name i.e., app-hello as shown below in
Line 11
Source code: [Link]
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyApp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link rel="icon" type="image/x-icon" href="[Link]">
</head>
<body>
<app-hello></app-hello></body></html>