3161611_Advanced Web Programming_Lab Manual (3) (1) (1)
3161611_Advanced Web Programming_Lab Manual (3) (1) (1)
B.E. Semester 6
(Information Technology)
L.D.College of Engineering,Ahmedabad
Certificate
Place:__________________
Date: __________________
Main motto of any laboratory/practical/field work is for enhancing required skills as well as
creating ability amongst students to solve real time problem by developing relevant
competencies in psychomotor domain. By keeping in view, GTU has designed competency
focused outcome-based curriculum for engineering degree programs where sufficient weightage
is given to practical work. It shows importance of enhancement of skills amongst the students
and it pays attention to utilize every second of time allotted for practical amongst students,
instructors and faculty members to achieve relevant outcomes by performing the experiments
rather than having merely study type experiments. It is must for effective implementation of
competency focused outcome-based curriculum that every practical is keenly designed to serve
as a tool to develop and enhance relevant competency required by the various industry among
every student. These psychomotor skills are very difficult to develop through traditional chalk
and board content delivery method in the classroom. Accordingly, this lab manual is designed to
focus on the industry defined relevant outcomes, rather than old practice of conducting practical
to prove concept and theory.
By using this lab manual students can go through the relevant theory and procedure in advance
before the actual performance which creates an interest and students can have basic idea prior
to performance. This in turn enhances pre-determined outcomes amongst students. Each
experiment in this manual begins with competency, industry relevant skills, course outcomes as
well as practical outcomes (objectives). The students will also achieve safety and necessary
precautions to be taken while performing practical.
This manual also provides guidelines to faculty members to facilitate student centric lab activities
through each experiment by arranging and managing necessary resources in order that the
students follow the procedures with required safety and necessary precautions to achieve the
outcomes. It also gives an idea that how students will be assessed by providing rubrics.
In the era of digitization, the demand of Internet based applications is increasing day by day.
Advanced Web Programming is one of the required skills for IT Engineer. This focuses on frontend
and back-end design. After learning this subject students can advance their career in the field of
web development.
Utmost care has been taken while preparing this lab manual however always there is chances of
improvement. Therefore, we welcome constructive suggestions for improvement and removal
of errors if any.
Sr.
Objective(s) of Experiment CO1 CO2 CO3 CO4 CO5
No.
6. Student shall develop the habits of evolving more ideas, innovations, skills etc. apart from
those included in scope of manual.
7. Student shall refer technical magazines and data books.
8. Student should develop a habit of submitting the experimentation work as per the schedule
and s/he should be well prepared for the same.
Index
(Progressive Assessment Sheet)
Sr. No. Objective(s) of Experiment Page Date of Date of Assessmen Sign. of Remark
No. perform submissi t Teacher s
ance on Marks with date
Total
Experiment No: 1
Date :
Relevant CO : CO 1
Objectives:
Theory:
• What is AJAX?
▪ AJAX = Asynchronous JavaScript And XML.
1. A browser built-in XMLHttpRequest object (to request data from a web server)
▪ AJAX allows web pages to be updated asynchronously by exchanging data with a web server
behind the scenes. This means that it is possible to update parts of a web page, without
reloading the whole page.
<head>
<script type="text/javascript">
function loadXMLDoc() {
req=new XMLHttpRequest();
req.onreadystatechange=function() {
document.getElementById("div1").innerHTML=req.responseText;}
req.open("GET","myinfo.txt",true);
req.send();}
</script>
</head>
<body>
</body>
</html>
Output:
Conclusion:
To design a webpage that reads a text file using Ajax, you will need to create an HTML file, a CSS
file, and a JavaScript file. The HTML file will contain the basic structure of the page, the CSS file
will style the page, and the JavaScript file will contain the code that reads the text file and
updates the page.
Quiz:
ANS:- AJAX stands for Asynchronous JavaScript and XML. It is a technique used in web development
to create interactive and dynamic web applications. With AJAX, web pages can send and receive data
3161611 Meet nikunjbhai dangi -210280116026
AWP-3161611 Viral Parag Parikh 210280116057
from a server asynchronously without interfering with the current page's behavior. This means that
when a user interacts with a web page, such as submitting a form or clicking a button, the page can
make requests to the server in the background without reloading the entire page.
• Enhanced User Experience: AJAX allows web pages to update content dynamically without
requiring the entire page to reload. This leads to a smoother and more responsive user
experience, as users can interact with the page without interruptions.
• Reduced Server Load: By using AJAX, only specific parts of a web page are updated, rather
than the entire page. This reduces the amount of data transferred between the client and
server, as well as the server processing load, leading to improved performance and scalability.
• Faster Load Times: Since AJAX requests can be made asynchronously, web pages can load
initial content quickly and then fetch additional data from the server in the background. This
can significantly reduce initial page load times, especially for complex web applications with
large amounts of data.
• Improved Interactivity: AJAX enables developers to create interactive web applications that
respond to user actions in real-time. This can include features such as auto-complete search
fields, live updates, and interactive forms, enhancing overall user engagement.
• Offline Capability: With proper implementation, AJAX can support offline browsing by caching
data on the client side. This allows users to access certain parts of the application even when
they are offline, improving accessibility and usability.
• Cross-Browser Compatibility: AJAX is supported by most modern web browsers, making it a
reliable and widely-compatible technology for building web applications. This ensures
consistent behavior across different platforms
• JSON Files: JSON (JavaScript Object Notation) has become more popular than XML for data
interchange in web applications. AJAX can efficiently read JSON files and parse them into
JavaScript objects for further processing.
• Text Files: AJAX can also read plain text files from the server. This can be useful for fetching
textual content, such as configuration files, logs, or other types of textual data.
• HTML Files: While less common, AJAX can retrieve HTML files from the server. This allows you
to fetch partial HTML content and dynamically update specific sections of a web page without
refreshing the entire page.
• CSV Files: AJAX can read Comma-Separated Values (CSV) files from the server. This is useful
for fetching tabular data that can be parsed and processed on the client side.
• Image Files: While AJAX itself cannot directly read binary image files, it can fetch image URLs
from the server and dynamically update image elements on the web page
Suggested Reference:
1. https://www.w3schools.com/xml/ajax_intro.asp
Assessment :
Understanding of Implementation of Presentation and report Total (10
Problem Problem writing (3 marks) marks)
(3 marks) (4 marks)
Experiment No: 2
Aim : Create a HTML form that will accept Enrolment No., Name, Semester, Branch,
Mobile Number, Email, Address etc. from the student and display them on the
page using Angular JS Directives and Expressions.
Date:
Relevant CO : CO 2
Objectives:
1. To understand HTML Page Structure.
2. To understand how to use Angular JS directives.
Theory:
• HTML Form : HTML Forms are required, when
▪ For example for registration you may collect information like user name , email , contact
number, address etc.
▪ A form will take input from the site visitor and then will post it to a back-end application such
as CGI, ASP Script or PHP script etc.
▪ The back-end application will perform required processing on the passed data based on
defined business logic inside the application.
▪ There are various form elements available like text fields, textarea fields, drop-down menus,
radio buttons, checkboxes, etc.
▪ The HTML <form> tag is used to create an HTML form
Syntax :
</form>
</textarea>
<option value =
"Physics">Physics</option>
</select>
▪ ng-model : This directive is used to bind the values of HTML controls to a variable.
▪ ng-bind : This directive is used to bind HTML elements to variables. It is generally used to
display the values of variables in the HTML elements like <p> or <span>.
▪ Angular JS Expression : Angular JS expressions are used to print the values of the variables on
the page. An Angular JS expression starts with {{ and ends with }}.
- For example, {{ first_name + “ “ + last_name }} will print first_name and last_name separated
by space.
Implementation: Create a HTML form that will accept Enrolment No., Name, Semester, Branch,
Mobile Number, Email, Address etc. from the student and display them on the page using Angular
JS Directives and Expressions.
<!DOCTYPE html>
<html lang="en" ng-app="studentApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Information Form</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<label for="name">Name:</label>
<input type="text" id="name" ng-model="studentCtrl.name"><br>
<label for="semester">Semester:</label>
<input type="text" id="semester" ng-model="studentCtrl.semester"><br>
<label for="branch">Branch:</label>
<input type="text" id="branch" ng-model="studentCtrl.branch"><br>
<label for="email">Email:</label>
<input type="email" id="email" ng-model="studentCtrl.email"><br>
<label for="address">Address:</label>
<textarea id="address" ng-model="studentCtrl.address"></textarea><br>
<div ng-show="studentCtrl.showInfo">
<h2>Student Information</h2>
<p><strong>Enrollment No:</strong> {{ studentCtrl.enrollmentNo }}</p>
<p><strong>Name:</strong> {{ studentCtrl.name }}</p>
<script>
var app = angular.module('studentApp', []);
app.controller('studentController', function() {
var vm = this;
vm.showInfo = false;
vm.displayInfo = function() {
vm.showInfo = true;
};
});
</script>
</body>
</html>
Output:
Conclusion:
We Created a HTML form that will accept Enrolment No., Name, Semester, Branch,
Mobile Number, Email, Address etc. from the student and display them on the
page using Angular JS Directives and Expressions
Quiz:
1. Enlist five most commonly used Angular JS directives and state their usages.
Ans:-
1.ng-model: This directive binds the value of HTML controls (input, select, textarea) to application
data. It provides two-way data binding, meaning changes in the model reflect in the view and vice
versa. Example: <input type="text" ng-model="user.name">.
2.ng-repeat: Used for repeating a set of HTML elements for each item in a collection. It iterates
over each item in an array or object and creates a copy of the HTML element for each item.
Example: <li ng-repeat="item in items">{{ item.name }}</li>.
3.ng-click: This directive binds a function to the click event of an HTML element. When the
element is clicked, the function specified by ng-click is executed. Example: <button ng-
click="submitForm()">Submit</button>.
4.ng-show / ng-hide: These directives conditionally show or hide HTML elements based on the
evaluation of an expression. ng-show shows the element if the expression evaluates to true, while
ng-hide hides it if the expression evaluates to true. Example: <div ng-
show="isLoggedIn">Welcome, {{ username }}</div>.
5.ng-if: This directive conditionally adds or removes the DOM element based on the evaluation
of an expression. It completely removes the element from the DOM if the expression evaluates
to false, otherwise, it recreates it. Example: <div ng-if="isAdmin">Admin Panel</div>.
2. Explain various ways to display the values of the variables on the page with suitable example.
Ans:-
1. Interpolation (Double Curly Braces):
Interpolation is the simplest way to display variable values directly within HTML markup using
double curly braces.
<p>Hello, {{ name }}</p>
2. ng-bind Directive:
Instead of using interpolation, you can use the ng-bind directive to bind data to an HTML
element. It is especially useful when dealing with HTML attributes like href, src, etc.
<a ng-bind="link">Link</a>
3. ng-model Directive:
If you want to display the value of an input field, you can use the ng-model directive. It binds
the value of an input field to a variable, and changes to the input field automatically reflect in
the bound variable.
3161611 Meet nikunjbhai dangi -210280116057
AWP-3161611 Meet nikunjbhai dangi 210280116057
<input type="text" ng-model="username">
<p>Hello, {{ username }}</p>
4. ng-repeat Directive:
When you need to display a list of items, you can use the ng-repeat directive to iterate over
each item in the list and display them dynamically.
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
5. Custom Functions or Filters:
You can define custom functions or filters in your AngularJS application to manipulate data
before displaying it on the page.
<p>Filtered Value: {{ value | customFilter }}</p>
6. Using Controllers:
If you're using controllers in your AngularJS application, you can assign variables to $scope and
access them directly in your HTML templates.
app.controller('ExampleController', function($scope) {
$scope.message = 'Hello, World!';
});
<div ng-controller="ExampleController">
<p>{{ message }}</p>
</div>
Suggested References:
1. https://www.w3schools.com/angular/angular_directives.asp
2. https://www.w3schools.com/angular/angular_model.asp
3. https://www.w3schools.com/angular/angular_databinding.asp
Assessment :
Understanding of Implementation of Presentation and report Total (10
marks)
Problem Problem writing
(3 marks) (4 marks) (3 marks)
Experiment No: 3
Aim :Create a webpage using Angular JS that displays details of students' objects
(such as Enrolment No., Name, Semester, Branch, Mobile Number, Email Address,
Address etc.) in a tabular format with appropriate CSS effects.
Date:
Relevant CO: CO 1, CO 2
Objectives:
• MVC Architecture
Model View Controller or MVC as it is popularly called, is a software design pattern for developing
web applications. A Model View Controller pattern is made up of the following three parts, ▪ Model
− It is the lowest level of the pattern responsible for maintaining data.
▪ View − It is responsible for displaying all or a portion of the data to the user.
▪ Controller − It is a software Code that controls the interactions between the Model and View.
MVC is popular because it isolates the application logic from the user interface layer and supports
separation of concerns. The controller receives all requests for the application and then works with
the model to prepare any data needed by the view. The view then uses the data prepared by the
controller to generate a final presentable response. The MVC abstraction can be graphically
represented as Figure 2.
▪ After defining an Angular JS application, it can be bind with a controller using ng-controller
directive.
▪ To define controller, first an application module must be defined in <script> tag using
app.controller('myCtrl', function($scope) {
$scope.students=[
{enrolment:'301',name:'Rajesh',semester:'3',branch:'I.T.'},
{enrolment:'501',name:'Ishwar',semester:'5',branch:'Production'},
{enrolment:'701',name:'Ronit',semester:'7',branch:'Mechanical'}];
});
Application controller is defined using app variable along with controller( ) function.
Controller( ) function takes two arguments, first is the name of controller, which is myCtrl
in our case and second is the callback function with a single variable that is $scope. $scope
is an object, that can be used to declare variables and objects within the controller and it
is accessible throughout the controller.
As it can be seen in the above code, students is an array of objects defined using $scope. Each
object contains various values including enrolment, name, semester and branch.
▪ Now to create separate rows for each objects in a table, the following syntax cab be used.
Here, ng-repeat directive will iterate over all the elements of students (array of objects) and
separate rows will be created for each object. Each time object will be accessed using x and
you will be able to print it’s variables using expression, such as, {{ x.enrolment } in
individual cells of a table row.
3161611 Meet nikunjbhai dangi -210280116026
AWP-3161611 Meet nikunjbhai dangi 210280116026
▪ HTML tables allow web developers to arrange data into rows and columns.
▪ The <table> tag defines an HTML table.
▪ table row is defined with a <tr> tag.
▪ table header is defined with a <th> tag.
▪ text in <th> elements are bold and centered.
▪ Each table data/cell is defined with a <td>.
▪ By default, the text in <td> elements are regular and left-aligned.
▪ colspan attribute is used to make a cell span more than one column.
▪ rowspan attriute is used to make a call span more than one row.
▪ cellpadding represents the distance between cell borders and the content within a cell. ▪ The
cellspacing attribute defines space between table cell
Implementation: Create your class time table using table tag, experiment with rowspan, colspan,
cellspacing and cellpadding attributes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Class Timetable</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<table cellspacing="5" cellpadding="10">
<caption>Class Timetable</caption>
<tr>
<th>Time/Day</th>
<th>Monday</th>
3161611 Meet nikunjbhai dangi -210280116026
AWP-3161611 Meet nikunjbhai dangi 210280116057
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
</tr>
<tr>
<td rowspan="2">8:00 AM - 9:00 AM</td>
<td rowspan="2">SE</td>
<td>MAD</td>
<td rowspan="2">SE</td>
<td rowspan="2">AWP</td>
<td>MAD</td>
</tr>
<tr>
<td>CNS</td>
<td>BDA /AI </td>
</tr>
<tr>
<td>9:00 AM - 10:00 AM</td>
<td>SE</td>
<td>AWP</td>
<td>CNS</td>
<td>BDA/AI</td>
<td>MAD</td>
</tr>
<tr>
<td colspan="6">Break</td>
</tr>
<tr>
<td>10:15 AM - 11:15 AM</td>
<td>SE</td>
<td>MAD</td>
<td>SE</td>
<td>AWP</td>
<td>MAD</td>
</tr>
<tr>
<td>11:15 AM - 12:15 PM</td>
<td>SE</td>
<td>AWP</td>
<td>CNS</td>
<td>BDA/AI</td>
<td>MAD</td>
</tr>
</table>
</body>
</html>
Output:
Conclusion:
We Created our class time table using table tag, experiment with rowspan, colspan,
cellspacing and cellpadding attributes.
Quiz:
Ans:_
1. Using Controllers:
If you're using controllers in your AngularJS application, you can assign variables to $scope and
access them directly in your HTML templates.
app.controller('ExampleController', function($scope) {
$scope.message = 'Hello, World!';
});
<div ng-controller="ExampleController">
<p>{{ message }}</p>
</div>
7. ng-repeat Directive:
When you need to display a list of items, you can use the ng-repeat directive to iterate over
each item in the list and display them dynamically.
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
Suggested Reference:
1. https://www.w3schools.com/angular/angular_directives.asp
2. https://www.w3schools.com/angular/angular_tables.asp
References used by the students:
Assessment :
Understanding of Implementation of Presentation and report Total (10
marks)
Problem Problem writing
(3 marks) (4 marks) (3 marks)
Experiment No: 4
Aim : Modify Practical 3 and provide a search field to search records on the top of
the page and also allow user to sort table according to the column values when
user clicks on a column using filter.
Date:
Competency and Practical Skills: HTML, CSS, MVC in Angular JS, Filters in Angular JS Relevant
CO: CO 1, CO 2
Objectives:
<ul>
Implementation: Modify Practical 3 and provide a search field to search records on the top of the
page and also allow user to sort table according to the column values when user clicks on a column
using filter.
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Class Timetable with Search and Sort</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 10px;
3161611 Meet nikunjbhai dangi -210280116026
AWP-3161611 Meet nikunjbhai dangi 210280116026
text-align: center;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-controller="TimetableController">
<input type="text" ng-model="search" placeholder="Search...">
<table>
<caption>Class Timetable</caption>
<thead>
<tr>
<th ng-click="sortBy('Time/Day')">Time/Day</th>
<th ng-click="sortBy('Monday')">Monday</th>
<th ng-click="sortBy('Tuesday')">Tuesday</th>
<th ng-click="sortBy('Wednesday')">Wednesday</th>
<th ng-click="sortBy('Thursday')">Thursday</th>
<th ng-click="sortBy('Friday')">Friday</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in timetable | filter:search | orderBy:sortByColumn">
<td>{{ row.time }}</td>
<td>{{ row.monday }}</td>
<td>{{ row.tuesday }}</td>
<td>{{ row.wednesday }}</td>
<td>{{ row.thursday }}</td>
<td>{{ row.friday }}</td>
</tr>
</tbody>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('TimetableController', function($scope) {
$scope.timetable = [
{ time: '8:00 AM - 9:00 AM', monday: 'AI', tuesday: 'cns', wednesday: 'awp', thursday:
'mad', friday: 'se' },
{ time: '9:00 AM - 10:00 AM', monday: 'se', tuesday: 'awp', wednesday: 'mad', thursday:
'cns', friday: 'ipdc' },
{ time: '10:15 AM - 11:15 AM', monday: 'awp', tuesday: 'ipdc', wednesday: 'ai', thursday:
'mad', friday: 'bda' },
{ time: '11:15 AM - 12:15 PM', monday: 'dav', tuesday: 'dav', wednesday: 'mad', thursday:
'mad', friday: 'party' }
];
$scope.sortByColumn = '';
$scope.sortBy = function(column) {
$scope.sortByColumn = column;
};
});
</script>
</body>
</html>
Output:
Conclusion:
We Modified Practical 3 and provide a search field to search records on the top of the page and
also allow user to sort table according to the column values when user clicks on a column using
filter
Suggested Reference:
1. https://www.w3schools.com/angular/angular_filters.asp
Assessment :
Understanding of Implementation of Presentation and report Total (10
marks)
Problem Problem writing
(3 marks) (4 marks) (3 marks)
Experiment No: 5
Aim : Write Angular JS code to read Customer’s data in JSON format available in a
Customers.php file using $http service and display the same on a webpage in
tabular format.
Date:
Competency and Practical Skills: HTML, JSON (JavaScript), PHP, Services in Angular JS Relevant
CO: CO 1, CO 2
Objectives:
- $http : It is used to request the resources available on the server and lets your application
handle the response.
▪ $http Service : The AngularJS $http service makes a request to the server, and returns a
response. The following code demonstrates the general use of $http service.
Here an object of $http service needs to be passed in the callback function of controller.
Which can further be used to request the resources available on the server. Here it tries to
access MyPage.php. If resource request is handled then the response will be available in
response variable and that can be used to further process the output as per the user’s
need.
Implementation: Write Angular JS code to read Customer’s data in JSON format available in a
Customers.php file using $http service and display the same on a webpage in tabular format.
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Customer Data</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-controller="CustomerController">
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="customer in customers">
<td>{{ customer.id }}</td>
<td>{{ customer.name }}</td>
<td>{{ customer.email }}</td>
<td>{{ customer.phone }}</td>
</tr>
</tbody>
</table>
</div>
<script>
var app = angular.module('myApp', []);
})
.catch(function(error) {
console.error('Error fetching customer data:', error);
});
});
</script>
</body>
</html>
Output:
Conclusion:
Written Angular JS code to read Customer’s data in JSON format available in a Customers.php
file using $http service and display the same on a webpage in tabular format
Quiz:
1. Explain the usage of any five services available in Angular JS with suitable examples.
ANS:-
1.$http Service: This service facilitates communication with remote HTTP servers. It allows
fetching data from a server, sending data to a server, and interacting with RESTful APIs.
2.$location Service: This service provides access to the browser's URL. It allows reading and
modifying the current URL, navigating to different routes within the application, and
retrieving URL parameters
3.$rootScope Service: This service provides the top-level scope for an AngularJS application.
It serves as the parent scope for all other scopes within the application..
4.$timeout Service: This service allows executing a function after a specified delay. It is
commonly used for asynchronous operations, such as delaying the execution of code or
implementing timeouts.
5.$filter Service: This service allows filtering arrays or objects in AngularJS templates. It
provides various built-in filters for formatting data, such as currency, date, number, uppercase,
lowercase, etc.
2. Write Angular JS code to display clock on the web page.
ANS:- <!DOCTYPE html>
<html ng-app="clockApp">
<head>
<title>AngularJS Clock</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="clockController.js"></script>
</head>
<body ng-controller="ClockController">
<h1>{{ currentTime }}</h1>
</body>
</html>
angular.module('clockApp', [])
.controller('ClockController', ['$scope', '$interval', function($scope, $interval) {
// Function to update the clock time
function updateTime() {
$scope.currentTime = new Date().toLocaleTimeString();
}
Suggested Reference:
1. https://www.w3schools.com/angular/angular_services.asp
2. https://www.w3schools.com/angular/angular_http.asp
Assessment :
Understanding of Implementation of Presentation and report Total (10
marks)
Problem Problem writing
(3 marks) (4 marks) (3 marks)
Experiment No: 6
Aim : Create an Angular JS application for validation that will accept Email,
Username and Password as required fields from the user. It will enable submit
button only if all the entered data are valid.
Date:
Relevant CO: CO 2
Objectives:
1. To understand the use of validation states / flags available in Angular JS for validating data
captured from the users
Theory:
1. $untouched : It is used to identify that the field has not been touched yet.
3. $pristine : It is used to identify that the field has not been modified yet.
2. $dirty : It is used to identify that one or more fields of the form have been modified.
5. $submitted : It is used to identify that the form is submitted They are all properties of
the form, and are either true or false.
<body ng-app="">
<form name="Form1">
Name: <input name="Name" ng-model="Name" required>
<span ng-show="Form1.Name.$touched && myForm.myName.$invalid">The name
is required.</span>
</form>
</body>
The above code shows an example of using these states / flags. In this code, an input field Name
of Form1 is validated using Form1.Name.$touched and myForm.myName.$invalid. If the input
control is modified then the value of Form1.Name.$touched will be true, otherwise false.
Similarly if the input control’s content is empty then the value of myForm.myName.$invalid will
be true, otherwise false.
Here, ng-show directive is used to show / hide the <span> element based on the result of the
flags. Thus, <span> element will be visible only if both the states / flags are true, means the
input control is modified and empty.
Similarly ng-enabled and ng-disabled directives can be used to enable or disable the controls in
the form. Both of these are assigned boolean values.
Implementation: Create an Angular JS application for validation that will accept Email, Username
and Password as required fields from the user. It will enable submit button only if all the entered
data are valid.
<!DOCTYPE html>
<html lang="en" ng-app="validationApp">
<head>
<meta charset="UTF-8">
<title>AngularJS Validation</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-controller="validationCtrl">
3161611 Meet nikunjbhai dangi -210280116026
AWP-3161611 Meet nikunjbhai dangi 210280116026
<label>Username:</label>
<input type="text" name="username" ng-model="user.username" required><br>
<span ng-show="userForm.username.$dirty && userForm.username.$invalid">Username
is required.</span><br>
<label>Password:</label>
<input type="password" name="password" ng-model="user.password" ng-minlength="6"
required><br>
<span ng-show="userForm.password.$dirty &&
userForm.password.$error.required">Password is required.</span>
<span ng-show="userForm.password.$dirty &&
userForm.password.$error.minlength">Password should be at least 6 characters
long.</span><br>
<script>
var app = angular.module('validationApp', []);
app.controller('validationCtrl', function($scope) {
$scope.submitForm = function() {
// Handle form submission logic here
alert('Form submitted successfully!');
};
});
</script>
</body>
</html>
Output:
Conclusion:
I had To understand the use of validation states / flags available in Angular JS for validating data
captured from the users
Quiz:
1. Briefly discuss the usage of all the Input states and Form states with suitable examples.
ANS:-
Input States:
1. $untouched: The input field has not been touched by the user yet
<input type="text" name="username" ng-model="user.username" ng-class="{ 'untouched':
userForm.username.$untouched }">
2. $touched: The input field has been touched by the user.
<input type="email" name="email" ng-model="user.email" ng-class="{ 'touched':
userForm.email.$touched }">
3. $pristine: The input field value has not been changed.
<input type="password" name="password" ng-model="user.password" ng-class="{ 'pristine':
userForm.password.$pristine }">
4. $dirty: The input field value has been changed.
<input type="text" name="username" ng-model="user.username" ng-class="{ 'dirty':
userForm.username.$dirty }">
5. $valid: The input value is valid based on validation rules.
<input type="text" name="username" ng-model="user.username" required ng-class="{ 'valid':
userForm.username.$valid }">
6. $invalids: The input value is invalid based on validation rules.
<input type="email" name="email" ng-model="user.email" ng-class="{ 'invalid':
userForm.email.$invalid }">
Form States:
1. $pristine: The form has not been interacted with yet
<form name="userForm" ng-class="{ 'pristine': userForm.$pristine }">
2. $dirty: At least one input field in the form has been changed.
<form name="userForm" ng-class="{ 'dirty': userForm.$dirty }">
3. $valid: All input fields in the form are valid.
<form name="userForm" ng-class="{ 'valid': userForm.$valid }">
4. $invalid: At least one input field in the form is invalid.
<form name="userForm" ng-class="{ 'invalid': userForm.$invalid }">
5. $submitted: The form has been submitted
<form name="userForm" ng-class="{ 'submitted': userForm.$submitted }">
2.Discuss various CSS classes present in Angular JS used for these validation states.
ANS:-
For Form Controls:
1. ng-valid: Applied to an input element when its value meets all validation requirements.
2. ng-invalid: Applied to an input element when its value does not meet validation
requirements.
3. ng-pristine: Applied to an input element when it has not been interacted with (i.e., its value
has not changed).
4. ng-dirty: Applied to an input element when its value has been changed.
5. ng-touched: Applied to an input element when it has been blurred or focused and then
blurred.
6. ng-untouched: Applied to an input element when it has not been blurred or focused.
For Forms:
1. ng-valid: Applied to a form element when all of its child input elements are valid.
2. ng-invalid: Applied to a form element when at least one of its child input elements is
invalid.
3. ng-pristine: Applied to a form element when none of its child input elements have been
interacted with.
4. ng-dirty: Applied to a form element when at least one of its child input elements has been
interacted with.
5. ng-submitted: Applied to a form element when the form has been submitted.
Suggested Reference:
1. https://www.w3schools.com/angular/angular_validation.asp
Assessment :
Understanding of Implementation of Presentation and report Total (10
marks)
Problem Problem writing
(3 marks) (4 marks) (3 marks)
Experiment No: 7
Relevant CO: CO 2
Objectives:
1. To understand how to create Single Page Application (SPA) using Angular JS Routing.
Theory:
In the second step, links to load the pages needs to be created. For example,
<a href="#!red">Red</a>
In the third step, ngRoute module must be included as a dependency in application module
using the following line,
Now your application has access to the route module, which provides the $routeProvider
object. In the fourth step, use this $routeProvider object to configure routing details in the
Angular JS application. The following code demonstrates the same,
app.config(function($routeProvider) {
$routeProvider
.when("/", { templateUrl :
"main.htm"
})
.when("/red", {
templateUrl : "red.htm"
})
.when("/green", {
templateUrl : "green.htm"
})
.when("/blue", {
templateUrl : "blue.htm"
});
});
In the above code, in when( ) function, two arguments needs to be passed, first is the target
URL and second is the block of statements to execute when target URL is requested. Here,
templateUrl is used to load HTML page as a template.
Now to load the content of resource specified by templateUrl, a view needs to be created.
This can be done using ng-view directive in three different ways.
<ng-view></ng-view>
<div ng-view></div>
<div class="ng-view"></div>
Once, the view is specified, the pages will be loaded in the view when the links are clicked.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/", {
template: " <h1> this is the base oage if everything</h1> ",
})
.when("/Porsche", {
template: "<h3> The Porsche 911 (pronounced Nine Eleven or in German: Neunelf) is a
two-door 2+2 high performance rear-engined sports car introduced in September 1964 by
Porsche AG of Stuttgart, Germany. It has a rear-mounted flat-six engine and originally a torsion
bar suspension. <br /><strong >Porsche 911 is a 4 seater Coupe with a mileage of 11 Kmpl
dependingupon it's transmission and fuel type. 911s 6 cylinder, 2981 cc, 2996 cc&6 Cylinders
Inline& 4 Valves/Cylinder& DOHC 379.50 bhp @ 6500 rpm can generate power and 465 Nm @
6300 torque. It has a fuel tank capacity of 64 Litres.</strong ></h3>"
})
.when("/BMW", {
template: "<h3> <strong>The BMW M5 price is Rs. 1.73 Crore and Audi RS6 price is Rs.
1.59Crore. The BMW M5 is available in 4395 cc engine with 1 fuel typeoptions: Petrol and Audi
RS6 is available in 3993 cc engine with 1 fueltype options: Petrol. M5 provides the mileage of 9.1
kmpl and RS6provides the mileage of 10.42 kmpl.</strong></h3>",
})
.when("/Toyota", {
template: " <h3>The legendary Mk4 Supra was propelled to fame by the immortal 2JZ
engine. The Mk4 Supra's immortality is due to the legendary 2JZ engine. This engine was over-
engineered to the point where it could produce over 1000 horsepower without requiring any
internal modifications. <strong>In his modified Mk4 Supra, a guy hit 197 mph on UK public roads
in 1999. He drove the car at more than 900 horsepower with two boost bars.</strong></h3>",
});
});
</script>
</head>
<body ng-app="myApp">
<ol>
<a href="#/!">Main</a>
<li><a href="#!Porsche">PORSCHE 911</a></li>
<li><a href="#!Toyota">TOYOTA SUPRA</a></li>
<li><a href="#!BMW">BMW M5</a></li>
</ol>
<div ng-view style="border:2px solid balck; border-radius: 30px; "></div>
</body>
</html>
Output:
Conclusion:
I had To understand how to create Single Page Application (SPA) using Angular JS Routing
Quiz:
},
controller: 'DashboardController'
})
Suggested Reference:
1. https://www.w3schools.com/angular/angular_routing.asp
Assessment :
Understanding of Implementation of Presentation and report Total (10
marks)
Problem Problem writing
(3 marks) (4 marks) (3 marks)
Experiment No: 8
Aim : Study the installation of Node JS and installation of various packages in Node
JS.
Date:
Relevant CO: CO 3
Objectives:
npm list -g
Output:
Conclusion:
I installed nodejs and required package in node js
Suggested Reference:
1. https://www.geeksforgeeks.org/15-npm-commands-that-every-node-js-developershould-
know/
Assessment :
Node JS installation Understanding of NPM Presentation and report Total (10
marks)
process (3 marks) writing
(4 marks) (3 marks)
Experiment No: 9
Aim : Design a webpage with a file input control to browse appropriate file and
four buttons Read File Synchronously, Read File Asynchronously, Compress File,
Decompress File. Implement the functionality of all four buttons on the browsed
file using Node JS.
Date :
Competency and Practical Skills: File System (fs) module and zlib modules of Node JS
Relevant CO : CO 3 Objectives:
1. To understand to difference between synchronous and asynchronous processes.
2. To understand the functions for compressing and decompressing files and use them.
Theory:
▪ Compressing a file
To compress a file first of all you need to read the file. createReadStream( ) function of file
system module allows you to read a file. It takes a single parameter that is the URL / Name
of the file to be read (along with the extension).
After reading a file you can compress it using zlib module’s createGzip( ) function.
Then you need to write the compressed file, that can be done using createWriteStream( )
function of file system module, again this function takes a single parameter, that is the
name of the file to be saved with.
In order to combine these function pipe( ) function can be used. It allows us to provide output
of one function as an input to the other one.
▪ Decompressing a file
Similarly to decompress a file you need to read the file using the same function previously
used createReadStream( ).
To decompress a file , use createGunzip( ) function of zlib module.
And again use createWriteStream( ) function to write a decompressed file.
Implementation : Design a webpage with a file input control to browse appropriate file and four
buttons Read File Synchronously, Read File Asynchronously, Compress File, Decompress File.
Implement the functionality of all four buttons on the browsed file using Node JS.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Operations</title>
</head>
<body>
<input type="file" id="fileInput">
<button onclick="readFileSync()">Read File Synchronously</button>
<button onclick="readFileAsync()">Read File Asynchronously</button>
<button onclick="compressFile()">Compress File</button>
<button onclick="decompressFile()">Decompress File</button>
<div id="output"></div>
<script src="script.js"></script>
</body>
</html>
function readFileSync() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (file) {
const formData = new FormData();
formData.append('file', file);
fetch('/readFileSync', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
document.getElementById('output').innerText = data;
})
.catch(error => console.error('Error:', error));
}
}
function readFileAsync() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (file) {
const formData = new FormData();
formData.append('file', file);
fetch('/readFileAsync', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
document.getElementById('output').innerText = data;
})
.catch(error => console.error('Error:', error));
}
}
function compressFile() {
// Implement compression logic
}
function decompressFile() {
// Implement decompression logic
}
Conclusion:
Quiz:
1. Enlist various functions available in fs module and also state their usages
ANS:-.
1. fs.readFile(path[, options], callback)
- Usage: Reads the contents of the file specified by `path`. The file content is passed to the
`callback` function.
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
2. fs.readFileSync(path[, options])
- Usage: Synchronously reads the contents of the file specified by `path` and returns the
content.
const fs = require('fs');
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
3. fs.writeFile(file, data[, options], callback)
- Usage: Writes data to the file specified by `file`. If the file does not exist, it will be created. If
the file exists, its contents will be replaced.
const fs = require('fs');
fs.writeFile('example.txt', 'Hello, world!', 'utf8', (err) => {
if (err) throw err;
console.log('File written successfully');
});
4. fs.writeFileSync(file, data[, options])
- Usage: Synchronously writes data to the file specified by `file`.
const fs = require('fs');
fs.writeFileSync('example.txt', 'Hello, world!', 'utf8');
console.log('File written successfully');
5. fs.appendFile(file, data[, options], callback)
- Usage: Appends data to the file specified by `file`. If the file does not exist, it will be created.
const fs = require('fs');
fs.appendFile('example.txt', 'New data to append', 'utf8', (err) => {
if (err) throw err;
console.log('Data appended to file');
});
6. fs.appendFileSync(file, data[, options])
- Usage: Synchronously appends data to the file specified by `file`.
const fs = require('fs');
fs.appendFileSync('example.txt', 'New data to append', 'utf8');
console.log('Data appended to file');
7. fs.readdir(path[, options], callback)
- Usage: Reads the contents of a directory specified by `path`. The directory contents are passed
to the `callback` function.
const fs = require('fs');
fs.readdir('.', (err, files) => {
if (err) throw err;
console.log(files);
});
8. fs.readdirSync(path[, options])
3161611 Meet nikunjbhai dangi -210280116026
AWP-3161611 Meet nikunjbhai dangi 210280116026
- Usage: Synchronously reads the contents of a directory specified by `path` and returns an array
of file names.
const fs = require('fs');
const files = fs.readdirSync('.');
console.log(files);
2. Explain various functions available in zlib module.
1. ANS:- zlib.deflate(buf, callback)
• Usage: Compresses the data in buf using the DEFLATE algorithm and calls the callback
function with the compressed data.
2. zlib.deflateSync(buf)
• Usage: Synchronously compresses the data in buf using the DEFLATE algorithm and
returns the compressed data.
3. zlib.inflate(buf, callback)
• Usage: Decompresses the data in buf using the DEFLATE algorithm and calls the
callback function with the decompressed data.
4. zlib.inflateSync(buf)
• Usage: Synchronously decompresses the data in buf using the DEFLATE algorithm and
returns the decompressed data.
5. zlib.gzip(buf, callback)
• Usage: Compresses the data in buf using the Gzip algorithm and calls the callback
function with the compressed data.
6. zlib.gzipSync(buf)
• Usage: Synchronously compresses the data in buf using the Gzip algorithm and
returns the compressed data.
7. zlib.gunzip(buf, callback)
• Usage: Decompresses the data in buf using the Gzip algorithm and calls the callback
function with the decompressed data.
8. zlib.gunzipSync(buf)
• Usage: Synchronously decompresses the data in buf using the Gzip algorithm and
returns the decompressed data.
9. zlib.brotliCompress(buf, callback)
• Usage: Compresses the data in buf using the Brotli algorithm and calls the callback
function with the compressed data.
10. zlib.brotliCompressSync(buf)
• Usage: Synchronously compresses the data in buf using the Brotli algorithm and
returns the compressed data.
11. zlib.brotliDecompress(buf, callback)
3161611 Meet nikunjbhai dangi -210280116026
AWP-3161611 Meet nikunjbhai dangi 210280116026
• Usage: Decompresses the data in buf using the Brotli algorithm and calls the callback
function with the decompressed data.
12. zlib.brotliDecompressSync(buf)
• Usage: Synchronously decompresses the data in buf using the Brotli algorithm and
returns the decompressed data.
Suggested Reference:
1. https://www.knowledgehut.com/blog/web-development/compression-decompressionof-
data-using-zlib-in-Nodejs#there-are-two-types-
ofcompression:%E2%80%AFlossless%E2%80%AFand%E2%80%AFlossy.
Assessment :
Understanding of Implementation of Presentation and report Total (10
Problem Problem writing (3 marks) marks)
(3 marks) (4 marks)
Experiment:-10
Aim:-Create a Node JS application that will allow a user to browse and upload a
file in localhost.
Date :
Competency and Practical Skills: File System (fs), http, and formidable modules of Node JS
Relevant CO : CO 3
Objectives:
1. To understand form processing while uploading any file on server in Node JS.
Theory:
In addition to formidable, file system (fs) and http modules will be required.
While designing the interface that will allow a user to browse the file to be uploaded, one
important thing to remember is to use post as a method and specify enctype attribute in <form>
tag, like,
After these modifications, your form will be able to upload the files on the server.
Now as shown bellow, using the IncomingForm( ) method of formidable module, the form can be
referred using a variable.
After that form variable can be used to parse the request object, fields and files using parse( )
function. Using appropriate methods of file system (fs) module, the uploaded file can be stored in
specific directory with appropriate name.
Implementation : Design a webpage with a file input control to browse appropriate file and four
buttons Read File Synchronously, Read File Asynchronously, Compress File, Decompress File.
Implement the functionality of all four buttons on the browsed file using Node JS.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Operations</title>
</head>
<body>
<input type="file" id="fileInput">
<button onclick="readFileSync()">Read File Synchronously</button>
<button onclick="readFileAsync()">Read File Asynchronously</button>
<button onclick="compressFile()">Compress File</button>
<button onclick="decompressFile()">Decompress File</button>
<div id="output"></div>
<script src="script.js"></script>
</body>
</html>
function readFileSync() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (file) {
const formData = new FormData();
formData.append('file', file);
fetch('/readFileSync', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
document.getElementById('output').innerText = data;
})
.catch(error => console.error('Error:', error));
}
}
function readFileAsync() {
3161611 Meet nikunjbhai dangi -210280116026
LDCE-028
if (file) {
const formData = new FormData();
formData.append('file', file);
fetch('/readFileAsync', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
document.getElementById('output').innerText = data;
})
.catch(error => console.error('Error:', error));
}
}
function compressFile() {
// Implement compression logic
}
function decompressFile() {
// Implement decompression logic
}
} else {
res.send(data);
}
});
});
Output:
Quiz:
1. Enlist and explain various methods of formidable module used to manage uploading files.
ANS;-
1. new formidable.IncomingForm([options]):
- Usage: Creates a new instance of `IncomingForm` with optional `options` for configuring the
form parsing behavior.
const formidable = require('formidable');
const form = new formidable.IncomingForm();
2. form.parse(req, callback):
- Usage: Parses the incoming form data from the specified `req` object. Calls the `callback`
function with two arguments: `err` and `fields` (containing form fields) and `files` (containing
uploaded files).
form.parse(req, (err, fields, files) => {
if (err) throw err;
console.log('Fields:', fields);
console.log('Files:', files);
});
3. form.on('file', function(field, file)):
- Usage: Event listener that is triggered when a file is received in the form data. Provides the
`field` name and `file` object containing information about the uploaded file.
form.on('file', (field, file) => {
console.log('Field:', field);
console.log('File:', file);
});
4. form.on('progress', function(bytesReceived, bytesExpected)):
- Usage: Event listener that is triggered during the file upload process, providing information
about the progress of the upload. form.on('progress', (bytesReceived, bytesExpected) => {
console.log('Progress:', (bytesReceived / bytesExpected) * 100 + '%');
});
5. form.on('error', function(err)):
- Usage: Event listener that is triggered when an error occurs during the form parsing process.
form.on('error', (err) => {
console.error('Error:', err);
});
6. form.uploadDir = '/path/to/upload/directory':
- Usage: Specifies the directory where uploaded files will be saved. If not specified, files will
be stored in the default temporary directory. form.uploadDir = '/path/to/upload/directory';
7. form.keepExtensions = true/false:
- Usage: Specifies whether to keep file extensions in the filenames of uploaded files. Default
is `false`. form.keepExtensions = true;
8. form.maxFileSize = sizeInBytes:
- Usage: Specifies the maximum allowed size for uploaded files. Files larger than this size will
be rejected. form.maxFileSize = 10 * 1024 * 1024; // 10 MB
Suggested Reference:
1. https://www.w3schools.com/nodejs/nodejs_uploadfiles.asp
Assessment :
Understanding of Implementation of Presentation and report Total (10
Problem Problem writing (3 marks) marks)
(3 marks) (4 marks)
EXPERIMENT:-11
Create a Node JS application that will allow a user to create new file, read
file, write into a file and delete a file.
Date :
Relevant CO : CO 3
Objectives:
2. appendFile( ) : It is used to append content in a file. If file doesn’t exists, new file will be
created.
3. open( ) : If open( ) is used with ‘w’ flag, it will allow user to write into a file. If file doesn’t
exists empty file will be created.
4. writeFile( ) : It is used to write a file. If file doesn’t exists, new file will be created.
Implementation : Create a Node JS application that will allow a user to create new file, read file,
write into a file and delete a file.
const fs = require('fs');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function readFile(filename) {
fs.readFile(filename, 'utf8', (err, data) => {
if (err) throw err;
console.log(`Content of '${filename}':`);
console.log(data);
});
}
function deleteFile(filename) {
fs.unlink(filename, (err) => {
if (err) throw err;
console.log(`File '${filename}' deleted successfully.`);
});
}
function promptUser() {
rl.question('Enter your choice (1: Create, 2: Read, 3: Write, 4: Delete, 5: Exit): ', (choice) => {
switch (choice) {
case '1':
rl.question('Enter filename: ', (filename) => {
rl.question('Enter content: ', (content) => {
createFile(filename, content);
promptUser();
});
});
break;
case '2':
rl.question('Enter filename: ', (filename) => {
readFile(filename);
promptUser();
});
break;
case '3':
rl.question('Enter filename: ', (filename) => {
rl.question('Enter content to append: ', (content) => {
writeToFile(filename, content);
promptUser();
});
});
break;
case '4':
rl.question('Enter filename to delete: ', (filename) => {
deleteFile(filename);
promptUser();
});
break;
case '5':
rl.close();
break;
default:
console.log('Invalid choice.');
promptUser();
break;
}
});
}
promptUser();
Output:
Conclusion:
I had To understand the basics of file management in Node JS
Practical Quiz:
1. Create Node JS application that will list all the files available in the browsed directory of a
server.
ANS:-
const http = require('http');
const fs = require('fs');
const path = require('path');
}
});
}
});
});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter your choice (1: Create File, 2: Rename File): ', (choice) => {
switch (choice) {
case '1':
rl.question('Enter filename: ', (filename) => {
rl.question('Enter content: ', (content) => {
createFile(filename, content);
});
});
break;
case '2':
rl.question('Enter current filename: ', (oldFilename) => {
rl.question('Enter new filename: ', (newFilename) => {
renameFile(oldFilename, newFilename);
});
});
break;
default:
console.log('Invalid choice.');
rl.close();
break;
}
});
Suggested Reference:
1. https://www.w3schools.com/nodejs/nodejs_filesystem.asp
Assessment :
Understanding of Implementation of Presentation and report Total (10
Problem Problem writing (3 marks) marks)
(3 marks) (4 marks)
EXPERIMENT:-12
Competency and Practical Skills: Operations on MongoDB Database, Node JS code for insertion in
MongoDB Database.
Relevant CO : CO 3, CO 4
Objectives:
• Introduction to MongoDB
MongoDB is a document database which is often referred to as a non-relational database. This
does not mean that relational data cannot be stored in document databases. It means that
relational data is stored differently. A better way to refer to it is as a non-tabular database.
MongoDB stores data in flexible documents. Instead of having multiple tables you can simply
keep all of your related data together. This makes reading your data very fast.
You can still have multiple groups of data too. In MongoDB, instead of tables these are called
collections.
MongoDB can be used locally or you can use the cloud platform for the same.
▪ And collection( ) function of Database object can be used to access the collection.
▪ In MongoDB the records are inserted in terms of documents, therefore the object of
document(s) to be inserted must be defined before performing insertion operation.
Implementation : Study MongoDB environment setup and write Node JS code to perform insertion
operation in Mongo DB.
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const dbName = 'mydatabase';
const client = new MongoClient(uri);
insertDocuments().catch(console.error);
Output:
Conclusion:
I had To understand the installation of MongoDB & how to interact with MongoDB Database
through Node JS code.
Practical Quiz:
2. Schema:
• Any changes to the schema often require altering the database schema,
which can be complex and may impact existing data.
3. Scalability:
• They can handle large volumes of data and high throughput by adding more
servers to the cluster.
4. Query Language:
• Document databases often provide their own query languages or APIs for
querying data.
• These query languages are typically designed to work with the document-
based data model and may offer features like nested queries, filtering, and
aggregation.
1. https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-windows/
2. https://www.w3schools.com/nodejs/nodejs_mongodb_insert.asp
Assessment :
Understanding of Implementation of Presentation and Total (10
Problem Problem report writing (3 marks)
(3 marks) (4 marks) marks)
Competency and Practical Skills: Operations on MongoDB Database, Node JS code for deletion in
MongoDB Database. Relevant CO : CO 3, CO 4
Objectives:
1. To understand how to delete documents from a MongoDB Database through Node JS code.
Theory:
▪ connect( ) function of MongoClient will allow a user to connect with a MongoDB database.
▪ Once the connection with the Database is established, collection( ) function of Database
object can be used to access the collection.
▪ After that create an object containing query data for a document to be deleted.
Implementation : Write Node JS code to perform deletion operation from Mongo DB.
Conclusion:
I had To understand how to delete documents from a MongoDB Database through Node JS
code
Suggested Reference:
1. https://www.w3schools.com/nodejs/nodejs_mongodb_query.asp
2. https://www.w3schools.com/nodejs/nodejs_mongodb_delete.asp
Assessment :
Understanding of Implementation of Presentation and report Total (10
Problem Problem writing (3 marks) marks)
(3 marks) (4 marks)
Competency and Practical Skills: Operations on MongoDB Database, Node JS code for selection
and updation of document in MongoDB Database.
Relevant CO : CO 3, CO 4
Objectives:
1. To understand how to search documents from a MongoDB Database and updated them
through Node JS code.
Theory:
▪ connect( ) function of MongoClient will allow a user to connect with the MongoDB
database.
▪ Once the connection with the Database is established, collection( ) function of Database
object can be used to access the collection.
▪ After that object containing query data for a document to be selected needs to be created.
▪ If the document is found then it’s details can be printed / used as per need.
Implementation : Write Node JS code to perform selection and updation operation to select and
update specific document in Mongo DB.
const { MongoClient, ObjectId } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'mydatabase';
async function selectAndUpdateDocument(collectionName, documentId, update) {
let client;
try {
client = new MongoClient(url);
await client.connect();
Conclusion:
I had To understand how to search documents from a MongoDB Database and updated them
through Node JS code.
Suggested Reference:
1. https://www.w3schools.com/nodejs/nodejs_mongodb_query.asp
2. https://www.w3schools.com/nodejs/nodejs_mongodb_update.asp
References used by the students:
Assessment :
Understanding of Implementation of Presentation and report Total (10
Problem Problem writing (3 marks) marks)
(3 marks) (4 marks)
AIM:-Create a single page application for Library that will allow the librarian to add
a new book and search whether book is currently available in the library or not.
Date :
Competency and Practical Skills: HTML, CSS, Angular JS, Node JS, MongoDB.
Relevant CO : CO 1, CO 2, CO 3, CO 4, CO 5
Objectives:
1. To learn application development using HTML, CSS, Angular JS and Node JS.
Implementation : Create a single page application for Library that will allow the librarian to add a
new book and search whether book is currently available in the library or not.
// backend/server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
// Connect to MongoDB
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.error('MongoDB connection error:', err));
// Book model
const Book = mongoose.model('Book', {
title: String,
author: String,
available: Boolean
});
// Middleware
app.use(bodyParser.json());
// frontend/app.js
const AddBook = {
template: `
<div>
<h2>Add New Book</h2>
<input v-model="title" type="text" placeholder="Title"><br>
<input v-model="author" type="text" placeholder="Author"><br>
<button @click="addBook">Add Book</button>
<p v-if="message">{{ message }}</p>
</div>
`,
data() {
return {
title: '',
author: '',
message: ''
};
},
methods: {
async addBook() {
try {
const response = await fetch('/api/books', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: this.title, author: this.author })
});
const data = await response.json();
this.message = `Book "${data.title}" added successfully`;
} catch (err) {
console.error('Error adding book:', err);
this.message = 'Failed to add book';
}
}
}
};
const SearchBooks = {
template: `
<div>
<h2>Search Books</h2>
<input v-model="query" type="text" placeholder="Search by Title"><br>
const routes = [
{ path: '/add-book', component: AddBook },
{ path: '/search-books', component: SearchBooks }
];
Conclusion:
I did learn application development using HTML, CSS, Angular JS and Node JS.
Suggested Reference:
1. https://www.w3schools.com/html/default.asp
2. https://www.w3schools.com/css/default.asp
3. https://www.w3schools.com/angular/
4. https://www.w3schools.com/nodejs/
5. https://www.w3schools.com/mongodb/index.php
3161611 Meet nikunjbhai dangi -210280116026
References used by the students:
Assessment :
Understanding of Implementation of Presentation and report Total (10
Problem Problem writing (3 marks) marks)
(3 marks) (4 marks)