SlideShare a Scribd company logo
Index
Assignment
NO:
Name of Practical Assignment Signature
1 Create an HTML form that contain the Student Registration
details and write a JavaScript to validate Student first and last
name as it should not contain other than alphabets and age
should be between 18 to 50.
2 Create an HTML form that contain the Employee Registration
details and write a JavaScript to validate DOB, Joining Date,
and Salary.
3 Create an HTML form for Login and write a JavaScript to
validate email ID using Regular Expression.
4 Write angular JS by using ng-click Directive to display an alert
message after clicking the element
5 Write an AngularJS script for addition of two numbers using
ng-init, ng-model & ng bind. And also Demonstrate ng-show,
ng-disabled, ng-click directives on button component.
6 Using angular js display the 10 student details in Table format
(using ng-repeat directive use Array to store data
7 Using angular js Create a SPA that show Syllabus content of all
subjects of MSC(CS) Sem II (use ng-view)
8 Using angular js create a SPA to accept the details such as
name, mobile number, pincode and email address and make
validation. Name should contain character only, SPPU M.Sc.
Computer Science Syllabus 2023-24 59 mobile number should
contain only 10 digit, Pincode should contain only 6 digit,
email id should contain only one @, . Symbol
9 Create an HTML form using AngularJS that contain the Student
Registration details and validate Student first and last name as it
should not contain other than alphabets and age should be
between 18 to 50 and display greeting message depending on
current time using ng-show (e.g. Good Morning, Good
Afternoon, etc.)(Use AJAX).
10 Create angular JS Application that show the current Date and
Time of the System(Use Interval Service)
11 Using angular js create a SPA to carry out validation for a
username entered in a textbox. If the textbox is blank, alert
„Enter username‟. If the number of characters is less than three,
alert ‟ Username is too short‟. If value entered is appropriate
the print „Valid username‟ and password should be minimum 8
characters
12 Create a Node.js file that will convert the output "Hello
World!" into upper-case letters
13 Using nodejs create a web page to read two file names from
user and append contents of first file into second file
14 Create a Node.js file that opens the requested file and returns
the content to the client If anything goes wrong, throw a 404
erro
15 Create a Node.js file that writes an HTML form, with an upload
field
16 Create a Node.js file that demonstrate create database and table
in MySQL
17 Create a node.js file that Select all records from the "customers"
table, and display the result object on console
18 Create a node.js file that Insert Multiple Records in "student"
table, and display the result object on console
19 Create a node.js file that Select all records from the "customers"
table, and delete the specified record.
20 Create a Simple Web Server using node js
21 Using node js create a User Login System
22 Write node js script to interact with the file system, and serve a
web page from a File
Assignment no: 1
Create an HTML form that contain the Student Registration details and write a
JavaScript to validate Student first and last name as it should not contain other than
alphabets and age should be between 18 to 50.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function validateName() {
var firstName = document.querySelector("#first-name").value;
var lastName = document.querySelector("#last-name").value;
var namePattern = /^[A-Za-z]+$/;
if (!namePattern.test(firstName) || !namePattern.test(lastName)) {
alert("Please enter valid first and last names (only alphabets).");
return false;
}
return true;
}
function validateAge() {
var age = parseInt(document.querySelector("#age").value);
if (isNaN(age) || age < 18 || age > 50) {
alert("Age must be between 18 and 50.");
return false;
}
return true;
}
function validateForm() {
var isValidName = validateName();
var isValidAge = validateAge();
if (isValidName && isValidAge) {
alert("Registration successful!");
return true;
} else {
alert("One or more fields are incorrectly set.");
return false;
}
}
</script>
</head>
<body>
<h2>STUDENT REGISTRATION FORM</h2>
<form name="registrationForm" method="post" onsubmit="return
validateForm()">
<label for="first-name">First Name:</label>
<input type="text" id="first-name" required><br>
<label for="last-name">Last Name:</label>
<input type="text" id="last-name" required><br>
<label for="age">Age:</label>
<input type="number" id="age" min="18" max="50" required><br>
<input type="submit" value="Register">
</form>
</body>
</html>
Output:
Assignment no: 2
Create an HTML form that contain the Employee Registration details and write a
JavaScript to validate DOB, Joining Date, and Salary.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Employee Registration Form</title>
<script type="text/javascript">
function validateDOB() {
var dob = document.querySelector("#dob").value;
var dobDate = new Date(dob);
var currentDate = new Date();
if (dobDate >= currentDate) {
alert("Please enter a valid Date of Birth.");
return false;
}
return true;
}
function validateJoiningDate() {
var joiningDate = document.querySelector("#joining-date").value;
var joiningDateDate = new Date(joiningDate);
if (joiningDateDate >= new Date()) {
alert("Joining Date cannot be in the future.");
return false;
}
return true;
}
function validateSalary() {
var salary = parseFloat(document.querySelector("#salary").value);
if (isNaN(salary) || salary <= 0) {
alert("Please enter a valid positive Salary amount.");
return false;
}
return true;
}
function validateForm() {
var isValidDOB = validateDOB();
var isValidJoiningDate = validateJoiningDate();
var isValidSalary = validateSalary();
if (isValidDOB && isValidJoiningDate && isValidSalary) {
alert("Employee registration successful!");
return true;
} else {
alert("One or more fields are incorrectly set.");
return false;
}
}
</script>
</head>
<body>
<h2>EMPLOYEE REGISTRATION FORM</h2>
<form name="employeeForm" onsubmit="return validateForm()">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" required><br>
<label for="joining-date">Joining Date:</label>
<input type="date" id="joining-date" required><br>
<label for="salary">Salary:</label>
<input type="number" id="salary" min="1" step="any" required><br>
<input type="submit" value="Register">
</form>
</body>
</html>
Output:
Assignment no: 3
Create an HTML form for Login and write a JavaScript to validate email ID using
Regular Expression.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Form</title>
<script type="text/javascript">
function validateEmail() {
var email = document.querySelector("#email").value;
var emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;
if (!emailPattern.test(email)) {
alert("Please enter a valid email address.");
return false;
}
return true;
}
function validateForm() {
var isValidEmail = validateEmail();
if (isValidEmail) {
alert("Login successful!");
return true;
} else {
alert("Invalid email address.");
return false;
}
}
</script>
</head>
<body>
<h2>LOGIN FORM</h2>
<form name="loginForm" onsubmit="return validateForm()">
<label for="email">Email:</label>
<input type="email" id="email" required><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Output:
Assignment no: 4
Write angular JS by using ng-click Directive to display an alert message after clicking
the element
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login Form</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="myApp">
<h2>LOGIN FORM</h2>
<div ng-controller="LoginController">
<label for="email">Email:</label>
<input type="email" id="email" ng-model="userEmail" required><br>
<button ng-click="showAlert()">Login</button>
</div>
<script>
angular.module('myApp', [])
.controller('LoginController', function ($scope) {
$scope.showAlert = function () {
alert('Login successful!'); // Display an alert message
};
});
</script>
</body>
</html>
Output:
Assignment no: 5
Write an AngularJS script for addition of two numbers using ng-init, ng-model &
ng bind. And also Demonstrate ng-show, ng-disabled, ng-click directives on button
component.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
<h2>Calculator</h2>
<p>First Number: <input type="number" ng-model="a" /></p>
<p>Second Number: <input type="number" ng-model="b" /></p>
<p>Sum: <span ng-bind="a + b"></span></p>
<button ng-click="calculateSum()" ng-show="a && b" ng-disabled="!a ||
!b">Calculate</button>
<script>
angular.module('myApp', [])
.controller('myCtrl', function ($scope) {
$scope.calculateSum = function () {
$scope.sum = $scope.a + $scope.b;
};
});
</script>
</body>
</html>
Output:
Assignment no: 6
Using angular js display the 10 student details in Table format (using ng-repeat
directive use Array to store data )
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
<h2>Student Details</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Roll Number</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="student in students">
<td>{{ student.name }}</td>
<td>{{ student.rollNumber }}</td>
<td>{{ student.grade }}</td>
</tr>
</tbody>
</table>
<script>
angular.module('myApp', [])
.controller('myCtrl', function ($scope) {
// Sample student data (you can replace this with your actual data)
$scope.students = [
{ name: 'Alice', rollNumber: '101', grade: 'A' },
{ name: 'Bob', rollNumber: '102', grade: 'B' },
{ name: 'Charlie', rollNumber: '103', grade: 'C' },
// Add more student objects here...
];
});
</script>
</body>
</html>
Assignment no: 7
Using angular js Create a SPA that show Syllabus content of all subjects of MSC(CS)
Sem II (use ng-view)
<!-- index.html -->
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-
route.min.js"></script>
</head>
<body>
<h1>MSC (CS) Semester II Syllabus</h1>
<p><a href ="#subject1">Design and Analsis of Algorithm</a></p>
<p><a href ="#subject2">Full Stack Development</a></p>
<div ng-view></div>
<script>
angular.module('myApp', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/subject1', {
templateUrl: 'subject1.html',
controller: 'Subject1Controller'
})
.when('/subject2', {
templateUrl: 'subject2.html',
controller: 'Subject2Controller'
})
// Add more routes for other subjects
.otherwise({
redirectTo: '/subject1' // Default route
});
})
.controller('Subject1Controller', function ($scope) {
// Load syllabus data for subject 1
// Example: $scope.syllabus = getSubject1Syllabus();
})
.controller('Subject2Controller', function ($scope) {
// Load syllabus data for subject 2
// Example: $scope.syllabus = getSubject2Syllabus();
});
</script>
</body>
</html>
Output:
Assignment no: 8
Using angular js create a SPA to accept the details such as name, mobile number,
pincode and email address and make validation. Name should contain character
only, SPPU M.Sc. Computer Science Syllabus 2023-24 59 mobile number should
contain only 10 digit, Pincode should contain only 6 digit, email id should contain
only one @, . Symbol
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
<h2>User Details</h2>
<form name="userForm">
<p>
<label for="name">Name:</label>
<input type="text" id="name" ng-model="user.name" required pattern="[A-
Za-z ]+">
</p>
<p>
<label for="mobile">Mobile Number:</label>
<input type="tel" id="mobile" ng-model="user.mobile" required pattern="[0-
9]{10}">
</p>
<p>
<label for="pincode">Pincode:</label>
<input type="text" id="pincode" ng-model="user.pincode" required
pattern="[0-9]{6}">
</p>
<p>
<label for="email">Email Address:</label>
<input type="email" id="email" ng-model="user.email" required>
</p>
<button ng-click="validateUser()" ng-
disabled="userForm.$invalid">Submit</button>
</form>
<div ng-show="submitted">
<h3>Submitted Details:</h3>
<p>Name: {{ user.name }}</p>
<p>Mobile Number: {{ user.mobile }}</p>
<p>Pincode: {{ user.pincode }}</p>
<p>Email Address: {{ user.email }}</p>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', function ($scope) {
$scope.user = {}; // Initialize user object
$scope.submitted = false;
$scope.validateUser = function () {
// Perform additional validation if needed
// For now, just mark as submitted
$scope.submitted = true;
};
});
</script>
</body>
</html>
Output:
Assignment no: 9
Create an HTML form using AngularJS that contain the Student Registration details
and validate Student first and last name as it should not contain other than
alphabets and age should be between 18 to 50 and display greeting message
depending on current time using ng-show (e.g. Good Morning, Good Afternoon,
etc.)(Use AJAX).
<!DOCTYPE html>
<html ng-app="studentApp">
<head>
<title>Student Registration Form</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
}
</style>
</head>
<body ng-controller="StudentController">
<h1>Student Registration Form</h1>
<form name="registrationForm" novalidate>
<p>
First Name:
<input
type="text"
name="firstName"
ng-model="student.firstName"
ng-pattern="/^[a-zA-Z]*$/"
required
/>
<span ng-show="registrationForm.firstName.$error.pattern">
First name should contain only alphabets.
</span>
</p>
<p>
Last Name:
<input
type="text"
name="lastName"
ng-model="student.lastName"
ng-pattern="/^[a-zA-Z]*$/"
required
/>
<span ng-show="registrationForm.lastName.$error.pattern">
Last name should contain only alphabets.
</span>
</p>
<p>
Age:
<input
type="number"
name="age"
ng-model="student.age"
min="18"
max="50"
required
/>
<span ng-show="registrationForm.age.$error.min ||
registrationForm.age.$error.max">
Age must be between 18 and 50.
</span>
</p>
<p>
<button type="submit">Register</button>
</p>
</form>
<div ng-show="greetingMessage">
<p>{{ greetingMessage }}</p>
</div>
<script>
angular.module('studentApp', []).controller('StudentController', function ($scope)
{
$scope.student = {
firstName: '',
lastName: '',
age: null,
};
// Determine the greeting message based on the current time
var currentTime = new Date().getHours();
if (currentTime >= 5 && currentTime < 12) {
$scope.greetingMessage = 'Good Morning!';
} else if (currentTime >= 12 && currentTime < 18) {
$scope.greetingMessage = 'Good Afternoon!';
} else {
$scope.greetingMessage = 'Good Evening!';
}
});
</script>
</body>
</html>
Output:
Assignment no: 10
Create angular JS Application that show the current Date and Time of the
System(Use Interval Service)
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Current Date and Time</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
</head>
<body ng-controller="MyController">
<h1>Current Date and Time</h1>
<p>The current time is: {{ theTime }}</p>
<script>
angular.module('myApp', []).controller('MyController', function ($scope,
$interval) {
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});
</script>
</body>
</html>
Output:
Assignment no: 11
Using angular js create a SPA to carry out validation for a username entered in a
textbox. If the textbox is blank, alert „Enter username‟. If the number of characters
is less than three, alert ‟ Username is too short‟. If value entered is appropriate the
print „Valid username‟ and password should be minimum 8 characters
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Username Validation</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
</head>
<body ng-controller="ValidationController">
<h1>Username Validation</h1>
<input type="text" ng-model="username" placeholder="Enter username">
<button ng-click="validateUsername()">Validate</button>
<div ng-show="validationMessage">
{{ validationMessage }}
</div>
<script>
angular.module('myApp', [])
.controller('ValidationController', function ($scope) {
$scope.validateUsername = function () {
if (!$scope.username) {
$scope.validationMessage = 'Enter username';
} else if ($scope.username.length < 3) {
$scope.validationMessage = 'Username is too short';
} else {
$scope.validationMessage = 'Valid username';
}
};
});
</script>
</body>
</html>
Output:
Assignment no: 12
Create a Node.js file that will convert the output "Hello World!" into upper-case
letters
var http = require('http');
var uc = require('upper-case');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(uc.upperCase("Hello World!"));
res.end();
}).listen(8080);
Output:
Assignment no: 13
Using nodejs create a web page to read two file names from user and append
contents of first file into second file
// Import necessary modules
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
// Create an Express app
const app = express();
// Middleware to parse form data
app.use(bodyParser.urlencoded({ extended: true }));
// Serve an HTML form to the user
app.get('/', (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(`
<html>
<body>
<h1>Select 2 files to append File1 contents to File2</h1>
<form method="post" action="/append">
<input type="text" name="file1" placeholder="Enter File1 name"
required><br>
<input type="text" name="file2" placeholder="Enter File2 name"
required><br>
<input type="submit" value="Append">
</form>
</body>
</html>
`);
res.end();
});
// Handle form submission
app.post('/append', (req, res) => {
const file1 = req.body.file1;
const file2 = req.body.file2;
// Read contents of File1
fs.readFile(file1, 'utf8', (err, data) => {
if (err) {
res.status(500).send(`Error reading ${file1}: ${err.message}`);
} else {
// Append contents of File1 to File2
fs.appendFile(file2, data, (appendErr) => {
if (appendErr) {
res.status(500).send(`Error appending to ${file2}: ${appendErr.message}`);
} else {
res.send(`Contents of ${file1} appended to ${file2}`);
}
});
}
});
});
// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Output:
Assignment no: 14
Create a Node.js file that opens the requested file and returns the content to the
client If anything goes wrong, throw a 404 error
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
// Extract the requested file name from the URL
const fileName = req.url.slice(1); // Remove the leading slash
// Construct the file path
const filePath = path.join(__dirname, fileName);
// Check if the file exists
fs.access(filePath, fs.constants.F_OK, (err) => {
if (err) {
// File not found (404 error)
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('File not found');
} else {
// Read the file and return its content
fs.readFile(filePath, 'utf8', (readErr, data) => {
if (readErr) {
// Error reading the file
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal server error');
} else {
// Successful response
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(data);
}
});
}
});
});
const port = process.env.PORT || 3000;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Output:
Assignment no: 15
Create a Node.js file that writes an HTML form, with an upload field
// Import the required modules
const http = require('http');
const formidable = require('formidable');
const fs = require('fs');
// Create an HTTP server
http.createServer(function (req, res) {
if (req.url === '/fileupload') {
// Handle file upload
const form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
if (err) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Error parsing form data.');
return;
}
// Move the uploaded file to a desired location
const oldPath = files.filetoupload.path;
const newPath = 'C:UsershrushDesktopcoding practiceweb' +
files.filetoupload.name; // Specify your desired path
fs.rename(oldPath, newPath, function (err) {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error moving file.');
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('File uploaded and moved successfully!');
});
});
} else {
// Display the upload form
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<form action="fileupload" method="post" enctype="multipart/form-
data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
res.end();
}
}).listen(3000);
Output:
Before
After submitting
Assignment no: 16
Create a Node.js file that demonstrate create database and table in MySQL
const mysql = require('mysql2');
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234'
});
con.connect(function (err) {
if (err) throw err;
console.log('Connected to MySQL server!');
con.query('CREATE DATABASE mydb', function (err, result) {
if (err) throw err;
console.log('Database "mydb" created successfully!');
});
//const mysql = require('mysql');
const con2 = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'mydb' // Specify the database you created earlier
});
con2.connect(function (err) {
if (err) throw err;
console.log('Connected to MySQL server!');
const createTableQuery = `
CREATE TABLE authors (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255)
)
`;
con2.query(createTableQuery, function (err, result) {
if (err) throw err;
console.log('Table "authors" created successfully!');
});
});
});
Output:
Assignment no: 17
Create a node.js file that Select all records from the "customers" table, and display
the result object on console
const mysql = require('mysql2');
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'mydb' // Replace with your actual database name
});
con.connect(function(err) {
if (err) throw err;
console.log('Connected to MySQL server!');
con.query('SELECT * FROM authors', function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Output:
Assignment no: 18
Create a node.js file that Insert Multiple Records in "student" table, and display the
result object on console.
const mysql = require('mysql2');
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'mydb' // Replace with your actual database name
});
con.connect(function(err) {
if (err) throw err;
console.log('Connected to MySQL server!');
// Data for multiple student records
const students = [
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 22 },
{ name: 'Charlie', age: 21 }
// Add more student objects as needed
];
// Prepare the SQL query for bulk insertion
const insertQuery = 'INSERT INTO student (name, age) VALUES ?';
const values = students.map(student => [student.name, student.age]);
// Execute the query
con.query(insertQuery, [values], function(err, result) {
if (err) throw err;
console.log('Inserted ' + result.affectedRows + ' rows into the "student" table.');
console.log('Last insert ID:', result.insertId);
});
con.query('SELECT * FROM student', function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Output:
Assignment no: 19
Create a node.js file that Select all records from the "customers" table, and delete
the specified record.
// select_and_delete.js
const mysql = require('mysql2');
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'mydb', // Replace with your database name
});
con.connect((err) => {
if (err) throw err;
// Select all records from the "customers" table
con.query('SELECT * FROM customers', (err, result) => {
if (err) throw err;
console.log('All records from "customers" table:');
console.log(result);
});
// Add this after the SELECT query
const addressToDelete = 'pune';
const deleteQuery = `DELETE FROM customers WHERE address =
'${addressToDelete}'`;
con.query(deleteQuery, (err, result) => {
if (err) throw err;
console.log(`Number of records deleted: ${result.affectedRows}`);
});
});
Output:
Assignment no: 20
Create a Simple Web Server using node js.
// index.js
const http = require('http');
const server = http.createServer((req, res) => {
res.write('This is the response from the server');
res.end();
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});
Output:
Assignment no: 21
Using node js create a User Login System.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple User Login</title>
</head>
<body>
<h1>User Login</h1>
<form action="/login" method="post">
<label for="username">Enter Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Enter Password:</label>
<input type="password" id="password" name="password" required>
<br>
<button type="submit">Login</button>
</form>
</body>
</html>
// app.js
const express = require('express');
const mysql = require('mysql2');
const app = express();
const PORT = 3000;
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'mydb', // Replace with your database name
});
db.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL database');
});
// Middleware to parse form data
app.use(express.urlencoded({ extended: true }));
// Serve the HTML form
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// Handle form submission
app.post('/login', (req, res) => {
const username = req.body.username;
const password = parseInt(req.body.password);
const query = `SELECT * FROM users WHERE username = '${username}' AND
password = '${password}'`;
db.query(query, [username, password], (err, results) => {
if (err) throw err;
if (results.length > 0) {
res.send(`Hello! ${username} Welcome to Dashboard`);
console.log(results);
} else {
res.send('Invalid credentials. Please try again.');
}
});
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running, and app is listening on port ${PORT}`);
});
Output:
Before login:
After login:
Assignment no: 22
Write node js script to interact with the file system, and serve a web page from a File
// File: server.js
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 8080;
http.createServer((req, res) => {
// Read the HTML file (index.html)
const filePath = path.join(__dirname, 'sample.html');
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error reading file');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
}).listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Output:

More Related Content

What's hot (20)

PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation Technique
Morshedul Arefin
 
PHP - Introduction to PHP Forms
PHP - Introduction to PHP FormsPHP - Introduction to PHP Forms
PHP - Introduction to PHP Forms
Vibrant Technologies & Computers
 
Java script array
Java script arrayJava script array
Java script array
chauhankapil
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
Max Claus Nunes
 
Client side and server side scripting
Client side and server side scriptingClient side and server side scripting
Client side and server side scripting
baabtra.com - No. 1 supplier of quality freshers
 
Web Building Blocks
Web Building BlocksWeb Building Blocks
Web Building Blocks
joegilbert
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
Shrinath Shenoy
 
Generics in java
Generics in javaGenerics in java
Generics in java
suraj pandey
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson
 
Top frontend web development tools
Top frontend web development toolsTop frontend web development tools
Top frontend web development tools
Benji Harrison
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
baabtra.com - No. 1 supplier of quality freshers
 
DYNAMIC HYPERTEXT MARKUP LANGUAGE (DHTML) & CSS WITH Application of JavaScript
DYNAMIC HYPERTEXT MARKUP LANGUAGE (DHTML) & CSS WITH Application of JavaScriptDYNAMIC HYPERTEXT MARKUP LANGUAGE (DHTML) & CSS WITH Application of JavaScript
DYNAMIC HYPERTEXT MARKUP LANGUAGE (DHTML) & CSS WITH Application of JavaScript
Soumen Santra
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validation
Maitree Patel
 
Dom
DomDom
Dom
Rakshita Upadhyay
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
WebStackAcademy
 
Css selectors
Css selectorsCss selectors
Css selectors
Parth Trivedi
 
Mongo Nosql CRUD Operations
Mongo Nosql CRUD OperationsMongo Nosql CRUD Operations
Mongo Nosql CRUD Operations
anujaggarwal49
 
Rspec
RspecRspec
Rspec
Amitai Barnea
 
Css
CssCss
Css
Hemant Saini
 

Similar to full stack practical assignment msc cs.pdf (20)

Mid term exam
Mid term examMid term exam
Mid term exam
H K
 
web-tech-lab-manual-final-abhas.pdf. Jer
web-tech-lab-manual-final-abhas.pdf. Jerweb-tech-lab-manual-final-abhas.pdf. Jer
web-tech-lab-manual-final-abhas.pdf. Jer
freshgammer09
 
YASH HTML CODES
YASH HTML CODESYASH HTML CODES
YASH HTML CODES
YashKoli22
 
YASH HTML CODE
YASH HTML CODE YASH HTML CODE
YASH HTML CODE
YashKoli22
 
WEB DESIGN PRACTICLE bca
WEB DESIGN PRACTICLE bcaWEB DESIGN PRACTICLE bca
WEB DESIGN PRACTICLE bca
YashKoli22
 
Sample app
Sample appSample app
Sample app
Ajaigururaj R
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
TYCS Visual Basic Practicals
TYCS Visual Basic PracticalsTYCS Visual Basic Practicals
TYCS Visual Basic Practicals
yogita kachve
 
Web technology practical list
Web technology practical listWeb technology practical list
Web technology practical list
desaipratu10
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
Knoldus Inc.
 
Data validation in web applications
Data validation in web applicationsData validation in web applications
Data validation in web applications
srkirkland
 
GCSECS-DefensiveDesign.pptx
GCSECS-DefensiveDesign.pptxGCSECS-DefensiveDesign.pptx
GCSECS-DefensiveDesign.pptx
azida3
 
Foundation and PathwaysCOS10020 Creating Web Application.docx
Foundation and PathwaysCOS10020 Creating Web Application.docxFoundation and PathwaysCOS10020 Creating Web Application.docx
Foundation and PathwaysCOS10020 Creating Web Application.docx
hanneloremccaffery
 
ITSC Internship Presentation
ITSC Internship PresentationITSC Internship Presentation
ITSC Internship Presentation
shabarish shabbi
 
Task 2
Task 2Task 2
Task 2
EdiPHP
 
Project1 CS
Project1 CSProject1 CS
Project1 CS
sunmitraeducation
 
Webtech File.docx
Webtech File.docxWebtech File.docx
Webtech File.docx
gambleryeager
 
Internet programming lab manual
Internet programming lab manualInternet programming lab manual
Internet programming lab manual
inteldualcore
 
2 coding101 fewd_lesson2_programming_overview 20210105
2 coding101 fewd_lesson2_programming_overview 202101052 coding101 fewd_lesson2_programming_overview 20210105
2 coding101 fewd_lesson2_programming_overview 20210105
John Picasso
 
Registration system in hostel
Registration system in hostelRegistration system in hostel
Registration system in hostel
sanjit_kumar
 
Mid term exam
Mid term examMid term exam
Mid term exam
H K
 
web-tech-lab-manual-final-abhas.pdf. Jer
web-tech-lab-manual-final-abhas.pdf. Jerweb-tech-lab-manual-final-abhas.pdf. Jer
web-tech-lab-manual-final-abhas.pdf. Jer
freshgammer09
 
YASH HTML CODES
YASH HTML CODESYASH HTML CODES
YASH HTML CODES
YashKoli22
 
YASH HTML CODE
YASH HTML CODE YASH HTML CODE
YASH HTML CODE
YashKoli22
 
WEB DESIGN PRACTICLE bca
WEB DESIGN PRACTICLE bcaWEB DESIGN PRACTICLE bca
WEB DESIGN PRACTICLE bca
YashKoli22
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
TYCS Visual Basic Practicals
TYCS Visual Basic PracticalsTYCS Visual Basic Practicals
TYCS Visual Basic Practicals
yogita kachve
 
Web technology practical list
Web technology practical listWeb technology practical list
Web technology practical list
desaipratu10
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
Knoldus Inc.
 
Data validation in web applications
Data validation in web applicationsData validation in web applications
Data validation in web applications
srkirkland
 
GCSECS-DefensiveDesign.pptx
GCSECS-DefensiveDesign.pptxGCSECS-DefensiveDesign.pptx
GCSECS-DefensiveDesign.pptx
azida3
 
Foundation and PathwaysCOS10020 Creating Web Application.docx
Foundation and PathwaysCOS10020 Creating Web Application.docxFoundation and PathwaysCOS10020 Creating Web Application.docx
Foundation and PathwaysCOS10020 Creating Web Application.docx
hanneloremccaffery
 
ITSC Internship Presentation
ITSC Internship PresentationITSC Internship Presentation
ITSC Internship Presentation
shabarish shabbi
 
Task 2
Task 2Task 2
Task 2
EdiPHP
 
Internet programming lab manual
Internet programming lab manualInternet programming lab manual
Internet programming lab manual
inteldualcore
 
2 coding101 fewd_lesson2_programming_overview 20210105
2 coding101 fewd_lesson2_programming_overview 202101052 coding101 fewd_lesson2_programming_overview 20210105
2 coding101 fewd_lesson2_programming_overview 20210105
John Picasso
 
Registration system in hostel
Registration system in hostelRegistration system in hostel
Registration system in hostel
sanjit_kumar
 
Ad

Recently uploaded (20)

June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Ad

full stack practical assignment msc cs.pdf

  • 1. Index Assignment NO: Name of Practical Assignment Signature 1 Create an HTML form that contain the Student Registration details and write a JavaScript to validate Student first and last name as it should not contain other than alphabets and age should be between 18 to 50. 2 Create an HTML form that contain the Employee Registration details and write a JavaScript to validate DOB, Joining Date, and Salary. 3 Create an HTML form for Login and write a JavaScript to validate email ID using Regular Expression. 4 Write angular JS by using ng-click Directive to display an alert message after clicking the element 5 Write an AngularJS script for addition of two numbers using ng-init, ng-model & ng bind. And also Demonstrate ng-show, ng-disabled, ng-click directives on button component. 6 Using angular js display the 10 student details in Table format (using ng-repeat directive use Array to store data 7 Using angular js Create a SPA that show Syllabus content of all subjects of MSC(CS) Sem II (use ng-view) 8 Using angular js create a SPA to accept the details such as name, mobile number, pincode and email address and make validation. Name should contain character only, SPPU M.Sc. Computer Science Syllabus 2023-24 59 mobile number should contain only 10 digit, Pincode should contain only 6 digit, email id should contain only one @, . Symbol 9 Create an HTML form using AngularJS that contain the Student Registration details and validate Student first and last name as it should not contain other than alphabets and age should be between 18 to 50 and display greeting message depending on current time using ng-show (e.g. Good Morning, Good Afternoon, etc.)(Use AJAX). 10 Create angular JS Application that show the current Date and Time of the System(Use Interval Service) 11 Using angular js create a SPA to carry out validation for a username entered in a textbox. If the textbox is blank, alert „Enter username‟. If the number of characters is less than three, alert ‟ Username is too short‟. If value entered is appropriate the print „Valid username‟ and password should be minimum 8 characters 12 Create a Node.js file that will convert the output "Hello World!" into upper-case letters 13 Using nodejs create a web page to read two file names from user and append contents of first file into second file 14 Create a Node.js file that opens the requested file and returns the content to the client If anything goes wrong, throw a 404 erro
  • 2. 15 Create a Node.js file that writes an HTML form, with an upload field 16 Create a Node.js file that demonstrate create database and table in MySQL 17 Create a node.js file that Select all records from the "customers" table, and display the result object on console 18 Create a node.js file that Insert Multiple Records in "student" table, and display the result object on console 19 Create a node.js file that Select all records from the "customers" table, and delete the specified record. 20 Create a Simple Web Server using node js 21 Using node js create a User Login System 22 Write node js script to interact with the file system, and serve a web page from a File
  • 3. Assignment no: 1 Create an HTML form that contain the Student Registration details and write a JavaScript to validate Student first and last name as it should not contain other than alphabets and age should be between 18 to 50. <!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript"> function validateName() { var firstName = document.querySelector("#first-name").value; var lastName = document.querySelector("#last-name").value; var namePattern = /^[A-Za-z]+$/; if (!namePattern.test(firstName) || !namePattern.test(lastName)) { alert("Please enter valid first and last names (only alphabets)."); return false; } return true; } function validateAge() { var age = parseInt(document.querySelector("#age").value); if (isNaN(age) || age < 18 || age > 50) { alert("Age must be between 18 and 50."); return false; } return true; } function validateForm() { var isValidName = validateName(); var isValidAge = validateAge(); if (isValidName && isValidAge) { alert("Registration successful!"); return true; } else { alert("One or more fields are incorrectly set."); return false; }
  • 4. } </script> </head> <body> <h2>STUDENT REGISTRATION FORM</h2> <form name="registrationForm" method="post" onsubmit="return validateForm()"> <label for="first-name">First Name:</label> <input type="text" id="first-name" required><br> <label for="last-name">Last Name:</label> <input type="text" id="last-name" required><br> <label for="age">Age:</label> <input type="number" id="age" min="18" max="50" required><br> <input type="submit" value="Register"> </form> </body> </html> Output: Assignment no: 2 Create an HTML form that contain the Employee Registration details and write a JavaScript to validate DOB, Joining Date, and Salary. <!DOCTYPE html> <html lang="en"> <head> <title>Employee Registration Form</title> <script type="text/javascript">
  • 5. function validateDOB() { var dob = document.querySelector("#dob").value; var dobDate = new Date(dob); var currentDate = new Date(); if (dobDate >= currentDate) { alert("Please enter a valid Date of Birth."); return false; } return true; } function validateJoiningDate() { var joiningDate = document.querySelector("#joining-date").value; var joiningDateDate = new Date(joiningDate); if (joiningDateDate >= new Date()) { alert("Joining Date cannot be in the future."); return false; } return true; } function validateSalary() { var salary = parseFloat(document.querySelector("#salary").value); if (isNaN(salary) || salary <= 0) { alert("Please enter a valid positive Salary amount."); return false; } return true; } function validateForm() { var isValidDOB = validateDOB(); var isValidJoiningDate = validateJoiningDate(); var isValidSalary = validateSalary(); if (isValidDOB && isValidJoiningDate && isValidSalary) { alert("Employee registration successful!"); return true; } else { alert("One or more fields are incorrectly set."); return false; } }
  • 6. </script> </head> <body> <h2>EMPLOYEE REGISTRATION FORM</h2> <form name="employeeForm" onsubmit="return validateForm()"> <label for="dob">Date of Birth:</label> <input type="date" id="dob" required><br> <label for="joining-date">Joining Date:</label> <input type="date" id="joining-date" required><br> <label for="salary">Salary:</label> <input type="number" id="salary" min="1" step="any" required><br> <input type="submit" value="Register"> </form> </body> </html> Output:
  • 7. Assignment no: 3 Create an HTML form for Login and write a JavaScript to validate email ID using Regular Expression. <!DOCTYPE html> <html lang="en"> <head> <title>Login Form</title> <script type="text/javascript"> function validateEmail() { var email = document.querySelector("#email").value; var emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/; if (!emailPattern.test(email)) { alert("Please enter a valid email address."); return false; } return true; } function validateForm() { var isValidEmail = validateEmail(); if (isValidEmail) { alert("Login successful!"); return true; } else { alert("Invalid email address."); return false; } } </script> </head> <body> <h2>LOGIN FORM</h2> <form name="loginForm" onsubmit="return validateForm()"> <label for="email">Email:</label> <input type="email" id="email" required><br> <input type="submit" value="Login"> </form> </body> </html> Output:
  • 8. Assignment no: 4 Write angular JS by using ng-click Directive to display an alert message after clicking the element <!DOCTYPE html> <html lang="en"> <head> <title>Login Form</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> </head> <body ng-app="myApp"> <h2>LOGIN FORM</h2> <div ng-controller="LoginController"> <label for="email">Email:</label> <input type="email" id="email" ng-model="userEmail" required><br> <button ng-click="showAlert()">Login</button> </div> <script> angular.module('myApp', []) .controller('LoginController', function ($scope) { $scope.showAlert = function () { alert('Login successful!'); // Display an alert message }; }); </script> </body> </html> Output:
  • 9. Assignment no: 5 Write an AngularJS script for addition of two numbers using ng-init, ng-model & ng bind. And also Demonstrate ng-show, ng-disabled, ng-click directives on button component. <!DOCTYPE html> <html ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body ng-controller="myCtrl"> <h2>Calculator</h2> <p>First Number: <input type="number" ng-model="a" /></p> <p>Second Number: <input type="number" ng-model="b" /></p> <p>Sum: <span ng-bind="a + b"></span></p> <button ng-click="calculateSum()" ng-show="a && b" ng-disabled="!a || !b">Calculate</button> <script> angular.module('myApp', []) .controller('myCtrl', function ($scope) { $scope.calculateSum = function () { $scope.sum = $scope.a + $scope.b; }; }); </script> </body> </html> Output:
  • 10. Assignment no: 6 Using angular js display the 10 student details in Table format (using ng-repeat directive use Array to store data ) <!DOCTYPE html> <html ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body ng-controller="myCtrl"> <h2>Student Details</h2> <table> <thead> <tr> <th>Name</th> <th>Roll Number</th> <th>Grade</th> </tr> </thead> <tbody> <tr ng-repeat="student in students">
  • 11. <td>{{ student.name }}</td> <td>{{ student.rollNumber }}</td> <td>{{ student.grade }}</td> </tr> </tbody> </table> <script> angular.module('myApp', []) .controller('myCtrl', function ($scope) { // Sample student data (you can replace this with your actual data) $scope.students = [ { name: 'Alice', rollNumber: '101', grade: 'A' }, { name: 'Bob', rollNumber: '102', grade: 'B' }, { name: 'Charlie', rollNumber: '103', grade: 'C' }, // Add more student objects here... ]; }); </script> </body> </html>
  • 12. Assignment no: 7 Using angular js Create a SPA that show Syllabus content of all subjects of MSC(CS) Sem II (use ng-view) <!-- index.html --> <!DOCTYPE html> <html ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular- route.min.js"></script> </head> <body> <h1>MSC (CS) Semester II Syllabus</h1> <p><a href ="#subject1">Design and Analsis of Algorithm</a></p> <p><a href ="#subject2">Full Stack Development</a></p> <div ng-view></div> <script> angular.module('myApp', ['ngRoute']) .config(function ($routeProvider) { $routeProvider .when('/subject1', { templateUrl: 'subject1.html', controller: 'Subject1Controller' }) .when('/subject2', { templateUrl: 'subject2.html', controller: 'Subject2Controller' }) // Add more routes for other subjects .otherwise({ redirectTo: '/subject1' // Default route }); }) .controller('Subject1Controller', function ($scope) { // Load syllabus data for subject 1 // Example: $scope.syllabus = getSubject1Syllabus();
  • 13. }) .controller('Subject2Controller', function ($scope) { // Load syllabus data for subject 2 // Example: $scope.syllabus = getSubject2Syllabus(); }); </script> </body> </html> Output:
  • 14. Assignment no: 8 Using angular js create a SPA to accept the details such as name, mobile number, pincode and email address and make validation. Name should contain character only, SPPU M.Sc. Computer Science Syllabus 2023-24 59 mobile number should contain only 10 digit, Pincode should contain only 6 digit, email id should contain only one @, . Symbol <!DOCTYPE html> <html ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body ng-controller="myCtrl"> <h2>User Details</h2> <form name="userForm"> <p> <label for="name">Name:</label> <input type="text" id="name" ng-model="user.name" required pattern="[A- Za-z ]+"> </p> <p> <label for="mobile">Mobile Number:</label> <input type="tel" id="mobile" ng-model="user.mobile" required pattern="[0- 9]{10}"> </p> <p> <label for="pincode">Pincode:</label> <input type="text" id="pincode" ng-model="user.pincode" required pattern="[0-9]{6}"> </p> <p> <label for="email">Email Address:</label> <input type="email" id="email" ng-model="user.email" required> </p> <button ng-click="validateUser()" ng- disabled="userForm.$invalid">Submit</button> </form> <div ng-show="submitted"> <h3>Submitted Details:</h3> <p>Name: {{ user.name }}</p> <p>Mobile Number: {{ user.mobile }}</p> <p>Pincode: {{ user.pincode }}</p> <p>Email Address: {{ user.email }}</p>
  • 15. </div> <script> angular.module('myApp', []) .controller('myCtrl', function ($scope) { $scope.user = {}; // Initialize user object $scope.submitted = false; $scope.validateUser = function () { // Perform additional validation if needed // For now, just mark as submitted $scope.submitted = true; }; }); </script> </body> </html>
  • 16. Output: Assignment no: 9 Create an HTML form using AngularJS that contain the Student Registration details and validate Student first and last name as it should not contain other than alphabets and age should be between 18 to 50 and display greeting message depending on current time using ng-show (e.g. Good Morning, Good Afternoon, etc.)(Use AJAX).
  • 17. <!DOCTYPE html> <html ng-app="studentApp"> <head> <title>Student Registration Form</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <style> body { font-family: Arial, sans-serif; } </style> </head> <body ng-controller="StudentController"> <h1>Student Registration Form</h1> <form name="registrationForm" novalidate> <p> First Name: <input type="text" name="firstName" ng-model="student.firstName" ng-pattern="/^[a-zA-Z]*$/" required /> <span ng-show="registrationForm.firstName.$error.pattern"> First name should contain only alphabets. </span> </p> <p> Last Name: <input type="text" name="lastName" ng-model="student.lastName" ng-pattern="/^[a-zA-Z]*$/" required /> <span ng-show="registrationForm.lastName.$error.pattern"> Last name should contain only alphabets. </span> </p> <p> Age: <input type="number" name="age"
  • 18. ng-model="student.age" min="18" max="50" required /> <span ng-show="registrationForm.age.$error.min || registrationForm.age.$error.max"> Age must be between 18 and 50. </span> </p> <p> <button type="submit">Register</button> </p> </form> <div ng-show="greetingMessage"> <p>{{ greetingMessage }}</p> </div> <script> angular.module('studentApp', []).controller('StudentController', function ($scope) { $scope.student = { firstName: '', lastName: '', age: null, }; // Determine the greeting message based on the current time var currentTime = new Date().getHours(); if (currentTime >= 5 && currentTime < 12) { $scope.greetingMessage = 'Good Morning!'; } else if (currentTime >= 12 && currentTime < 18) { $scope.greetingMessage = 'Good Afternoon!'; } else { $scope.greetingMessage = 'Good Evening!'; } }); </script> </body> </html> Output:
  • 19. Assignment no: 10 Create angular JS Application that show the current Date and Time of the System(Use Interval Service) <!DOCTYPE html> <html ng-app="myApp"> <head> <title>Current Date and Time</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script> </head> <body ng-controller="MyController"> <h1>Current Date and Time</h1> <p>The current time is: {{ theTime }}</p> <script> angular.module('myApp', []).controller('MyController', function ($scope, $interval) {
  • 20. $interval(function () { $scope.theTime = new Date().toLocaleTimeString(); }, 1000); }); </script> </body> </html> Output: Assignment no: 11 Using angular js create a SPA to carry out validation for a username entered in a textbox. If the textbox is blank, alert „Enter username‟. If the number of characters is less than three, alert ‟ Username is too short‟. If value entered is appropriate the print „Valid username‟ and password should be minimum 8 characters <!DOCTYPE html> <html ng-app="myApp"> <head> <title>Username Validation</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script> </head> <body ng-controller="ValidationController"> <h1>Username Validation</h1> <input type="text" ng-model="username" placeholder="Enter username"> <button ng-click="validateUsername()">Validate</button> <div ng-show="validationMessage">
  • 21. {{ validationMessage }} </div> <script> angular.module('myApp', []) .controller('ValidationController', function ($scope) { $scope.validateUsername = function () { if (!$scope.username) { $scope.validationMessage = 'Enter username'; } else if ($scope.username.length < 3) { $scope.validationMessage = 'Username is too short'; } else { $scope.validationMessage = 'Valid username'; } }; }); </script> </body> </html> Output:
  • 22. Assignment no: 12 Create a Node.js file that will convert the output "Hello World!" into upper-case letters var http = require('http'); var uc = require('upper-case'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(uc.upperCase("Hello World!")); res.end(); }).listen(8080); Output: Assignment no: 13 Using nodejs create a web page to read two file names from user and append contents of first file into second file // Import necessary modules const fs = require('fs');
  • 23. const express = require('express'); const bodyParser = require('body-parser'); // Create an Express app const app = express(); // Middleware to parse form data app.use(bodyParser.urlencoded({ extended: true })); // Serve an HTML form to the user app.get('/', (req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(` <html> <body> <h1>Select 2 files to append File1 contents to File2</h1> <form method="post" action="/append"> <input type="text" name="file1" placeholder="Enter File1 name" required><br> <input type="text" name="file2" placeholder="Enter File2 name" required><br> <input type="submit" value="Append"> </form> </body> </html> `); res.end(); }); // Handle form submission app.post('/append', (req, res) => { const file1 = req.body.file1; const file2 = req.body.file2; // Read contents of File1 fs.readFile(file1, 'utf8', (err, data) => { if (err) { res.status(500).send(`Error reading ${file1}: ${err.message}`); } else { // Append contents of File1 to File2 fs.appendFile(file2, data, (appendErr) => { if (appendErr) { res.status(500).send(`Error appending to ${file2}: ${appendErr.message}`); } else { res.send(`Contents of ${file1} appended to ${file2}`); }
  • 24. }); } }); }); // Start the server const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server running on port ${port}`); }); Output: Assignment no: 14 Create a Node.js file that opens the requested file and returns the content to the client If anything goes wrong, throw a 404 error const http = require('http'); const fs = require('fs'); const path = require('path'); const server = http.createServer((req, res) => { // Extract the requested file name from the URL const fileName = req.url.slice(1); // Remove the leading slash // Construct the file path const filePath = path.join(__dirname, fileName); // Check if the file exists fs.access(filePath, fs.constants.F_OK, (err) => { if (err) { // File not found (404 error) res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('File not found');
  • 25. } else { // Read the file and return its content fs.readFile(filePath, 'utf8', (readErr, data) => { if (readErr) { // Error reading the file res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Internal server error'); } else { // Successful response res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(data); } }); } }); }); const port = process.env.PORT || 3000; server.listen(port, () => { console.log(`Server running on port ${port}`); }); Output:
  • 26. Assignment no: 15 Create a Node.js file that writes an HTML form, with an upload field // Import the required modules const http = require('http'); const formidable = require('formidable'); const fs = require('fs'); // Create an HTTP server http.createServer(function (req, res) { if (req.url === '/fileupload') { // Handle file upload const form = new formidable.IncomingForm(); form.parse(req, function (err, fields, files) { if (err) { res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Error parsing form data.'); return; } // Move the uploaded file to a desired location const oldPath = files.filetoupload.path; const newPath = 'C:UsershrushDesktopcoding practiceweb' + files.filetoupload.name; // Specify your desired path fs.rename(oldPath, newPath, function (err) { if (err) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Error moving file.'); return; } res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('File uploaded and moved successfully!'); }); }); } else { // Display the upload form res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<form action="fileupload" method="post" enctype="multipart/form- data">'); res.write('<input type="file" name="filetoupload"><br>'); res.write('<input type="submit">'); res.write('</form>'); res.end(); }
  • 28. Assignment no: 16 Create a Node.js file that demonstrate create database and table in MySQL const mysql = require('mysql2'); const con = mysql.createConnection({ host: 'localhost', user: 'root', password: '1234' }); con.connect(function (err) { if (err) throw err; console.log('Connected to MySQL server!'); con.query('CREATE DATABASE mydb', function (err, result) { if (err) throw err; console.log('Database "mydb" created successfully!'); }); //const mysql = require('mysql'); const con2 = mysql.createConnection({ host: 'localhost', user: 'root', password: '1234', database: 'mydb' // Specify the database you created earlier }); con2.connect(function (err) { if (err) throw err; console.log('Connected to MySQL server!'); const createTableQuery = ` CREATE TABLE authors ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255) ) `; con2.query(createTableQuery, function (err, result) { if (err) throw err; console.log('Table "authors" created successfully!'); });
  • 29. }); }); Output: Assignment no: 17 Create a node.js file that Select all records from the "customers" table, and display the result object on console const mysql = require('mysql2'); const con = mysql.createConnection({ host: 'localhost', user: 'root', password: '1234', database: 'mydb' // Replace with your actual database name }); con.connect(function(err) { if (err) throw err; console.log('Connected to MySQL server!'); con.query('SELECT * FROM authors', function (err, result, fields) { if (err) throw err; console.log(result); }); }); Output:
  • 30. Assignment no: 18 Create a node.js file that Insert Multiple Records in "student" table, and display the result object on console. const mysql = require('mysql2'); const con = mysql.createConnection({ host: 'localhost', user: 'root', password: '1234', database: 'mydb' // Replace with your actual database name }); con.connect(function(err) { if (err) throw err; console.log('Connected to MySQL server!'); // Data for multiple student records const students = [ { name: 'Alice', age: 20 }, { name: 'Bob', age: 22 }, { name: 'Charlie', age: 21 } // Add more student objects as needed ]; // Prepare the SQL query for bulk insertion const insertQuery = 'INSERT INTO student (name, age) VALUES ?'; const values = students.map(student => [student.name, student.age]); // Execute the query con.query(insertQuery, [values], function(err, result) { if (err) throw err; console.log('Inserted ' + result.affectedRows + ' rows into the "student" table.'); console.log('Last insert ID:', result.insertId); }); con.query('SELECT * FROM student', function (err, result, fields) { if (err) throw err; console.log(result); }); }); Output:
  • 31. Assignment no: 19 Create a node.js file that Select all records from the "customers" table, and delete the specified record. // select_and_delete.js const mysql = require('mysql2'); const con = mysql.createConnection({ host: 'localhost', user: 'root', password: '1234', database: 'mydb', // Replace with your database name }); con.connect((err) => { if (err) throw err; // Select all records from the "customers" table con.query('SELECT * FROM customers', (err, result) => { if (err) throw err; console.log('All records from "customers" table:'); console.log(result); }); // Add this after the SELECT query const addressToDelete = 'pune'; const deleteQuery = `DELETE FROM customers WHERE address = '${addressToDelete}'`; con.query(deleteQuery, (err, result) => { if (err) throw err; console.log(`Number of records deleted: ${result.affectedRows}`); });
  • 32. }); Output: Assignment no: 20 Create a Simple Web Server using node js. // index.js const http = require('http'); const server = http.createServer((req, res) => { res.write('This is the response from the server'); res.end(); }); server.listen(3000, () => { console.log('Server is running at http://localhost:3000/'); }); Output:
  • 33. Assignment no: 21 Using node js create a User Login System. <!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple User Login</title> </head> <body> <h1>User Login</h1> <form action="/login" method="post"> <label for="username">Enter Username:</label> <input type="text" id="username" name="username" required> <br> <label for="password">Enter Password:</label> <input type="password" id="password" name="password" required> <br> <button type="submit">Login</button> </form> </body> </html> // app.js const express = require('express'); const mysql = require('mysql2'); const app = express(); const PORT = 3000; const db = mysql.createConnection({ host: 'localhost', user: 'root', password: '1234', database: 'mydb', // Replace with your database name }); db.connect((err) => { if (err) throw err; console.log('Connected to MySQL database'); }); // Middleware to parse form data app.use(express.urlencoded({ extended: true }));
  • 34. // Serve the HTML form app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); // Handle form submission app.post('/login', (req, res) => { const username = req.body.username; const password = parseInt(req.body.password); const query = `SELECT * FROM users WHERE username = '${username}' AND password = '${password}'`; db.query(query, [username, password], (err, results) => { if (err) throw err; if (results.length > 0) { res.send(`Hello! ${username} Welcome to Dashboard`); console.log(results); } else { res.send('Invalid credentials. Please try again.'); } }); }); // Start the server app.listen(PORT, () => { console.log(`Server is running, and app is listening on port ${PORT}`); });
  • 36. Assignment no: 22 Write node js script to interact with the file system, and serve a web page from a File // File: server.js const http = require('http'); const fs = require('fs'); const path = require('path'); const PORT = 8080; http.createServer((req, res) => { // Read the HTML file (index.html) const filePath = path.join(__dirname, 'sample.html'); fs.readFile(filePath, (err, data) => { if (err) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Error reading file'); } else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(data); } }); }).listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); }); Output: