0% found this document useful (0 votes)
9 views

3161611_Advanced Web Programming_Lab Manual (3) (1) (1)

This document is a laboratory manual for the Advanced Web Programming course (3161611) for B.E. Semester 6 students in Information Technology. It outlines the course objectives, practical experiments, and expected industry-relevant skills, emphasizing hands-on experience in web development using technologies like HTML, CSS, Angular JS, Node JS, and MongoDB. The manual also includes guidelines for faculty and students, assessment rubrics, and a certificate of completion for practical work.

Uploaded by

Meet Dangi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

3161611_Advanced Web Programming_Lab Manual (3) (1) (1)

This document is a laboratory manual for the Advanced Web Programming course (3161611) for B.E. Semester 6 students in Information Technology. It outlines the course objectives, practical experiments, and expected industry-relevant skills, emphasizing hands-on experience in web development using technologies like HTML, CSS, Angular JS, Node JS, and MongoDB. The manual also includes guidelines for faculty and students, assessment rubrics, and a certificate of completion for practical work.

Uploaded by

Meet Dangi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

A Laboratory Manual for

Advanced Web Programming


(3161611)

B.E. Semester 6
(Information Technology)

Directorate of Technical Education, Gandhinagar,


Gujarat

L.D.College of Engineering,Ahmedabad

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

Certificate

This is to certify that Mr./Ms. ____Meet nikunjbhai dangi __ Enrollment No.


___210280116026__ of B.E. Semester 6th Information Technology of this
Institute has satisfactorily completed the Practical / Tutorial work for the
subject Advanced Web Programming (3161611) for the academic year
2023-24.

Place:__________________
Date: __________________

Name and Sign of Faculty member Head of the Department

Advanced Web Programming (3161611)


3161611 Meet nikunjbhai dangi -210280116026
Preface

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.

3161611 Meet nikunjbhai dangi -210280116026


Advanced Web Programming (3161611)

Practical – Course Outcome matrix

Course Outcomes (COs):


CO 1 : Learn the concepts of client side programming using CSS and Java Script
CO 2 : Understand the concepts of Angular JS to extend basic HTML features
CO 3 : Learn Node JS framework to build dynamic server side applications
CO 4 : Study the concept of database using Mongo DB and connect database with application.
CO 5 : Design and implement full featured web application using the concepts of Angular JS and
Node JS.

Sr.
Objective(s) of Experiment CO1 CO2 CO3 CO4 CO5
No.

1. Design a webpage that reads a Text file using AJAX. √

Create a HTML form that will accept Enrolment No.,


Name, Semester, Branch, Mobile Number, Email, Address
2. √
etc. from the student and display them on the page using
Angular JS Directives and Expressions.

Create a webpage using Angular JS that displays details


of students' objects (such as Enrolment No., Name,
3. Semester, Branch, Mobile Number, Email Address, √ √
Address etc.) in a tabular format with appropriate CSS
effects.

Modify Practical 3 and provide a search field to search


records on the top of the page and also allow user to sort
4. √ √
table according to the column values when user clicks on
a column using filter.

Write Angular JS code to read Customer’s data in JSON


format available in a Customers.php file using $http
5. √ √
service and display the same on a webpage in tabular
format.

Create an Angular JS application for validation that will


accept Email, Username and Password as required fields
6. √
from the user. It will enable submit button only if all the
entered data are valid.

3161611 Meet nikunjbhai dangi -210280116026


Advanced Web Programming (3161611) Meet nikunjbhai dangi 210280116026

Create an example demonstrating the concept of Angular


7. √
JS Routing.

Study the installation of Node JS and installation of various


8. √
packages in Node JS.

Design a webpage with a file input control to browse


appropriate file and four buttons Read File
9. Synchronously, Read File Asynchronously, Compress File, √
Decompress File. Implement the functionality of all four
buttons on the browsed file using Node JS.

Create a Node JS application that will allow a user to


10. √
browse and upload a file in localhost.

Create a Node JS application that will allow a user to


11. √
create new file, read file, write into a file and delete a file.

Study MongoDB environment setup and write Node JS


12. √ √
code to perform insertion operation in Mongo DB.

Write Node JS code to perform deletion operation from


13. √ √
Mongo DB.

Write Node JS code to perform selection and updation


14. operation to select and update specific document in √ √
Mongo DB.

Create a single page application for Library that will allow


15. the librarian to add a new book and search whether book √ √ √ √ √
is currently available in the library or not.

3161611 Meet nikunjbhai dangi -210280116026


Advanced Web Programming (3161611)

Industry Relevant Skills


The following industry relevant competency are expected to be developed in the student by
undertaking the practical work of this laboratory.
1. HTML/CSS Skills : HTML is used extensively by web developers to build web pages. CSS is
used to implement different fonts, colors and layouts in the design of a website.
2. Angular JS Skills : Angular JS is used to create fully functional dynamic web applications.
3. Node JS Skills : Node JS is extensively used to support back end activities in the development
of dynamic web applications.
4. Web Development Skills : Angular JS, Node JS are widely used for the development of web
applications along with HTML and CSS.

Guidelines for Faculty members


1. Teacher should provide the guideline with demonstration of practical to the students with
all features.
2. Teacher shall explain basic concepts/theory related to the experiment to the students
before starting of each practical
3. Involve all the students in performance of each experiment.
4. Teacher is expected to share the skills and competencies to be developed in the students
and ensure that the respective skills and competencies are developed in the students after
the completion of the experimentation.
5. Teachers should give opportunity to students for hands-on experience after the
demonstration.
6. Teacher may provide additional knowledge and skills to the students even though not
covered in the manual but are expected from the students by concerned industry.
7. Give practical assignment and assess the performance of students based on task assigned
to check whether it is as per the instructions or not.
8. Teacher is expected to refer complete curriculum of the course and follow the guidelines
for implementation.

Instructions for Students


1. Students have to write answers / solutions of QUIZ in separate file pages. The quiz of
corresponding practical must be attached just behind each practical.
2. Students are expected to carefully listen to all the theory classes delivered by the faculty
members and understand the COs, content of the course, teaching and examination
scheme, skill set to be developed etc.
3. Students shall organize the work in the group and make record of all observations.
4. Students shall develop maintenance skill as expected by industries.
5. Student shall attempt to develop related hand-on skills and build confidence.

3161611 Meet nikunjbhai dangi -210280116026


Advanced Web Programming (3161611) Meet nikunjbhai dangi 210280116026

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.

Sample Rubrics for Practical Assessment :

Understanding of Implementation of Presentation and report Total (10


marks)
Problem Problem writing
(3 marks) (4 marks) (3 marks)

Excellent Moderate level Problem not


understanding understanding of
understood and
of problem problem and
and 03 relevance with the 02 can't establish the 01
Understanding relevance with the theory clearly relation with the
of Problem theory clearly understood.
theory.
understood.

Efficient Moderate level of Partial


implementation implementation. implementation 01
Implementation with proper 04 Poor naming 03 with poor to
of Problem understanding.
naming convention
convention. 02
and understanding

Presentation Unique Ordinary Weak


documentation documentation of documentation of 01
and report
(not copied from given problem with
given problem
writing other sources) of 03 proper formatting 02 to
without proper
given problem with and language 02
formatting and
proper formatting language
and language.

3161611 Meet nikunjbhai dangi -210280116026


Advanced Web Programming (3161611)

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

Design a webpage that reads a Text file using


1
AJAX.
Create a HTML form that will accept Enrolment
No., Name, Semester, Branch, Mobile Number,
2 Email, Address etc. from the student and display
them on the page using Angular JS Directives
and Expressions.

Create a webpage using Angular JS that displays


details of students' objects (such as Enrolment
3 No., Name, Semester, Branch, Mobile Number,
Email Address, Address etc.) in a tabular format
with appropriate CSS effects.
Modify Practical 3 and provide a search field to
search records on the top of the page and also
4 allow user to sort table according to the column
values when user clicks on a column using filter.
Write Angular JS code to read Customer’s data in
JSON format available in a Customers.php file
5 using $http service and display the same on a
webpage in tabular format.
Create an Angular JS application for validation
that will accept Email, Username and Password
6 as required fields from the user. It will enable
submit button only if all the entered data are
valid.

Create an example demonstrating the concept of


7
Angular JS Routing.
Study the installation of Node JS and installation of
8
various packages in Node JS.
Design a webpage with a file input control to
browse appropriate file and four buttons Read
File Synchronously, Read File Asynchronously,
9 Compress File, Decompress File. Implement the
functionality of all four buttons on the browsed
file using Node JS.

Create a Node JS application that will allow a user


10
to browse and upload a file in localhost.

3161611 Meet nikunjbhai dangi -210280116026


Advanced Web Programming (3161611) Meet nikunjbhai dangi 210280116026

Create a Node JS application that will allow a


11 user to create new file, read file, write into a file
and delete a file.
Study MongoDB environment setup and write
12 Node JS code to perform insertion operation in
Mongo DB.
Write Node JS code to perform deletion operation
13
from Mongo DB.
Write Node JS code to perform selection and
14 updation operation to select and update specific
document in Mongo DB.
Create a single page application for Library that
will allow the librarian to add a new book and
15 search whether book is currently available in the
library or not.

Total

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116057

Experiment No: 1

Aim : Design a webpage that reads a Text file using AJAX.

Date :

Competency and Practical Skills: HTML, JavaScript, XMLHttpRequest Object

Relevant CO : CO 1

Objectives:

1. To understand how AJAX can be used to load dynamic content.

Theory:

• What is AJAX?
▪ AJAX = Asynchronous JavaScript And XML.

▪ AJAX is not a programming language.

▪ It just uses a combination of:

1. A browser built-in XMLHttpRequest object (to request data from a web server)

2. JavaScript and HTML DOM (to display or use the data)

▪ 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.

• How AJAX works?

Figure 1. Working of AJAX

3161611 Meet nikunjbhai dangi -210280116057


AWP-3161611 Viral Parag Parikh 210280116026

▪ An event occurs in a web page (the page is loaded, a button is clicked).

▪ An XMLHttpRequest object is created by JavaScript.


▪ The XMLHttpRequest object sends a request to a web server.
▪ The server processes the request.
▪ The server sends a response back to the web page.
▪ The response is read by JavaScript.
▪ Proper action (like page update) is performed by JavaScript.

Implementation : Design a webpage that reads a Text file using AJAX.


<html>

<head>

<script type="text/javascript">

function loadXMLDoc() {

req=new XMLHttpRequest();

req.onreadystatechange=function() {

if (req.readyState==4 && req.status==200) {

document.getElementById("div1").innerHTML=req.responseText;}

req.open("GET","myinfo.txt",true);

req.send();}

</script>
</head>

<body>

<div id="div1">my first ajax program</div>

<input type="button" id="button1" value="click me!" onclick="loadXMLDoc()"/>

</body>

</html>

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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:

1. What is AJAX? Enlist the advantages of AJAX.

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

2. Which type of files can be read using AJAX?


Ans:- XML Files: AJAX was originally designed to work with XML files, and it can easily read and parse
XML data retrieved from the server.

• 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

3161611 Meet nikunjbhai dangi -210280116057


AWP-3161611 Meet nikunjbhai dangi 210280116026

Suggested Reference:

1. https://www.w3schools.com/xml/ajax_intro.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)

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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:

Competency and Practical Skills : HTML, Angular JS Directives

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 action = "Script URL" method = "GET|POST">

form elements like input, textarea etc.

</form>

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Viral Parag Parikh 210280116026

▪ Important form attributes are as given below

▪ HTML Form Controls

Control Name Used for Sample Code

Text input control


Textbox is used for
Single line text input accepting text from user, <input type = "text" name =
control like firstname, lastname "first_name" />
etc

Password input Password input control is


control used to accept password
from user. < input type = "password" name =
"password" />

Text Area Teaxtarea is used to accept


Multiline input multiline text input , like
comments. <textarea rows = "5" cols = "50" name
control. = "description">

Enter description here...

</textarea>

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

Checkbox Checkboxes are used when


<input type = "checkbox" name =
more than one option is
"maths" value = “maths"> Maths
required to be selected.
<input type = "checkbox" name =
"physics" value = “physics"> name =
"password" />

Radio Button Radio buttons are used


when out of many options,
just one option is required <input type = "radio" name =
to be selected. "subject" value = "maths"/> Maths

<input type = "radio" name =


"subject" value = "physics"/> Physics

Drop Down Box provides option to list


down various options in <select name = "dropdown">
the form of drop down list,
from where a user can <option value = "Maths"
select one or more options. selected>Maths</option>

<option value =
"Physics">Physics</option>

</select>

File Upload It allows site users to


upload a file to website.it is <input type = "file" name =
also known as file select
"fileupload" accept = "image/*" />
box.

Submit Button This creates a button that


automatically submits a
form. <input type = "submit" name =
"submit" value = "Submit" />

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Viral Parag Parikh 210280116026

Reset Button This creates a button that


automatically resets form
controls to their initial
<input type = "reset" name = "reset"
values.
value = "Reset" />

Button <input type = "button" name = "ok"


This creates a button that is
used to trigger a clientside value = "OK" />
script when the user clicks
that button.

Image Button This creates a clickable <input type = "image" name =


button but we can use an "imagebutton" src =
image as background of "/html/images/logo.png" />
the button.

Hidden Control <input type = "hidden" name =


Hidden form controls are
used to hide data inside "pagename" value = "10" />
the page which later on
can be pushed to the
server. This control hides
inside the code and does
not appear on the actual
page.

• Angulr JS Concepts to be used


To use Angular JS in web pages, angular.min.js file must be included in the current page using
<script src=”angular.min.js” /> tag in head section of the web page.

▪ 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.

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Viral Parag Parikh 210280116026

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>

<div ng-controller="studentController as studentCtrl">


<h2>Student Information Form</h2>
<form>
<label for="enrollmentNo">Enrollment No:</label>
<input type="text" id="enrollmentNo" ng-model="studentCtrl.enrollmentNo"><br>

<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="mobile">Mobile Number:</label>


<input type="text" id="mobile" ng-model="studentCtrl.mobile"><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>

<button type="button" ng-click="studentCtrl.displayInfo()">Submit</button>


</form>

<div ng-show="studentCtrl.showInfo">
<h2>Student Information</h2>
<p><strong>Enrollment No:</strong> {{ studentCtrl.enrollmentNo }}</p>
<p><strong>Name:</strong> {{ studentCtrl.name }}</p>

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

<p><strong>Semester:</strong> {{ studentCtrl.semester }}</p>


<p><strong>Branch:</strong> {{ studentCtrl.branch }}</p>
<p><strong>Mobile Number:</strong> {{ studentCtrl.mobile }}</p>
<p><strong>Email:</strong> {{ studentCtrl.email }}</p>
<p><strong>Address:</strong> {{ studentCtrl.address }}</p>
</div>
</div>

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

3161611 Viral Parag Parikh -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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

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)

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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:

Competency and Practical Skills: HTML, CSS, Use of MVC in Angular JS

Relevant CO: CO 1, CO 2

Objectives:

1. To understand about defining objects in Angular JS.


2. To use objects defined in Angular JS and display it’s information in HTML table.
Theory:

• 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.

Figure 2. MVC Architecture

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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.

• Angular JS concepts to be used

▪ To define an Angular JS application scope ng-app directive must be used.

▪ 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

var app = angular.module('myApp', [ ]);

Here angular.module ( ) function is used to define application module. Where myApp is


the name of application and [ ] (empty square brackets) are used to mention no additional
/ dependant modules are needed / used.

▪ Then using app variable controller can be defined as

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.

▪ A table must be created using <table> tag.

▪ Now to create separate rows for each objects in a table, the following syntax cab be used.

<tr ng-repeat="x in students">

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 Table Tag

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

3161611 Viral Parag Parikh -210280116026


AWP-3161611 Viral Parag Parikh 210280116026

</body>
</html>

Output:

Conclusion:
We Created our class time table using table tag, experiment with rowspan, colspan,
cellspacing and cellpadding attributes.

Quiz:

1. Write a note on : MVC Architecture.


Ans:- Model: The Model represents the data and the business logic of the application. It
encapsulates the data access, data manipulation, and business rules. Essentially, it is responsible
for managing the application's data structure and ensuring its integrity. In a web application, the
Model interacts with the database or any other data source to retrieve or update data.
View: The View is responsible for presenting the data to the user and handling the user interface.
It represents the user interface components such as HTML pages, forms, buttons, and other visual
elements. The View receives data from the Model and renders it to the user. It is important to
note that the View should be as passive as possible and should not contain any business logic.
Controller: The Controller acts as an intermediary between the Model and the View. It receives
user input from the View, processes it (typically by invoking methods on the Model), and updates
the View accordingly. The Controller handles user interactions and application flow. It delegates
tasks to the Model for data manipulation and to the View for displaying information to the user.
The key benefits of using the MVC architecture include:

3161611 Viral Parag Parikh -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

Modularity: MVC separates concerns, allowing developers to focus on individual components


without affecting others. This promotes code reusability and simplifies maintenance.
Scalability: Since the components are loosely coupled, it's easier to scale the application by
adding or modifying components without affecting the entire system.
Testability: Each component can be tested independently, facilitating unit testing and ensuring
the application's reliability.
Maintainability: With clear separation of concerns, it's easier to maintain and update the
application over time. Changes in one component are less likely to affect other components.

2. Explain the usage of ng-repeat, ng-controller directives with suitable example.

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)

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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:

1. To understand about defining objects in Angular JS.


2. To use objects defined in Angular JS and display it’s information in HTML table.
3. To use filter to filter the records.
Theory:

Angular JS concepts to be used


▪ Filters in Angular JS : Filters in Angular JS are used to format / transform the data. Angular
JS provides the following filters.

- currency : It is used to format a number to a currency format.

- date : It is used to format a date to a specified format.

- filter : It is used to select a subset of items from an array.

- json : It formats an object to a JSON string.

- limitTo : It limits an array/string, into a specified number of elements/characters.

- lowercase : It is used to format a string to lower case.

- number : It formats a number to a string.

- orderBy : It orders / sorts an array by an expression.

- uppercase : It is used to format a string to upper case.


For example,

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

<ul>

<li ng-repeat="x in names | filter : 'i'">


{{ x }}
</li>
</ul>
The above code will display an unordered list of items from names array consisting ‘i' as a
character.
<ul>

<li ng-repeat="x in persons | orderBy:'country'">


{{ x.name + ', ' + x.country }}
</li>
</ul>
Similarly the above code will display the name and country of all the elements of persons
array separated by comma in an unordered list, and this list will be sorted by value of
country variable of each object.

▪ Defining functions in Angular JS


In Angular JS functions can be defined inside the controller using $scope object. The general
syntax to define a function is,

$scope.function_name = function(value1, value2, ...) {


//body of the function
}

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' },

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Viral Parag Parikh 210280116026

{ 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

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)

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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:

1. To understand the use of services in Angular JS.


Theory:

Angular JS concepts to be used


▪ Services in Anguar JS : In AngularJS, a service is a function, or object, that is available for,
and limited to, your AngularJS application. AngularJS has more than 30 built-in services.
Some of the most commonly used services are,

- $location : It is used to get the location of the current webpage (URL).

- $http : It is used to request the resources available on the server and lets your application
handle the response.

- $timeout : It is similar to setTimeout( ) function of JavaScript. It is used to perform an


activity when time outs.

- $interval : It is similar to setInterval( ) function of JavaScript. It is used to perform some


task repeatedly at some interval.

▪ $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.

<script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope,


$http) {
$http.get("MyPage.php").then(function(response) {
$scope.myData = response.data.records;
});
}); </script>

Here an object of $http service needs to be passed in the callback function of controller.

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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', []);

app.controller('CustomerController', function($scope, $http) {


$http.get('Customers.php')
.then(function(response) {
$scope.customers = response.data;
3161611 Meet nikunjbhai dangi -210280116026
AWP-3161611 Meet nikunjbhai dangi 210280116026

})
.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.

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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

// Initial call to update time


updateTime();

// Update time every second


var intervalPromise = $interval(updateTime, 1000);

// Cancel interval when scope is destroyed to prevent memory leaks


$scope.$on('$destroy', function() {
$interval.cancel(intervalPromise);
});
}]);

Suggested Reference:

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

1. https://www.w3schools.com/angular/angular_services.asp
2. https://www.w3schools.com/angular/angular_http.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)

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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:

Competency and Practical Skills: HTML, Validation states / flags Angular JS

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:

Angular JS concepts to be used


▪ Validation states / flags in Anguar JS : Angular JS provides facility to observe the changes
made in the form controls through various states / flags. Some of the states are related to
input controls and some can be used for forms.

- Input fields have the following states:

1. $untouched : It is used to identify that the field has not been touched yet.

2. $touched : It is used to identify that the field has been touched.

3. $pristine : It is used to identify that the field has not been modified yet.

4. $dirty : It is used to identify that the field has been modified.

5. $invalid : It is used to identify that the field content is not valid.

6. $valid : It is used to identify that the field content is valid.


They are all properties of the input field, and are either true or false.

- Forms have the following states:

1. $pristine : It is used to identify that no fields have been modified yet.

2. $dirty : It is used to identify that one or more fields of the form have been modified.

3. $invalid : It is used to identify that the form content is not valid.

4. $valid : It is used to identify that the form content is valid.

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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

<form name="userForm" novalidate>


<label>Email:</label>
<input type="email" name="email" ng-model="user.email" required><br>
<span ng-show="userForm.email.$dirty && userForm.email.$invalid">Invalid
email.</span><br>

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

<button type="submit" ng-disabled="userForm.$invalid" ng-


click="submitForm()">Submit</button>
</form>
</div>

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

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

Conclusion:
I had To understand the use of validation states / flags available in Angular JS for validating data
captured from the users

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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 }">

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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

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)

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

Experiment No: 7

Aim : Create an example demonstrating the concept of Angular JS Routing.


Date:

Competency and Practical Skills: HTML, Routing in Angular JS

Relevant CO: CO 2

Objectives:

1. To understand how to create Single Page Application (SPA) using Angular JS Routing.
Theory:

Angular JS concepts to be used


▪ Routing in Anguar JS : In Angular JS, ngRoute module helps in configuring routing information
to create Single Page Applications.
In order to use ngRoute module, first the developer need to include angular-route.js file using
the following line in <head> section.

<script src=”angular-route.js” />

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,

var app = angular.module("myApp", ["ngRoute"]);

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,

3161611 Meet nikunjbhai dangi -210280116057


AWP-3161611 Meet nikunjbhai dangi 210280116026

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.

1. Using ng-view directive can be used as HTML element.

<ng-view></ng-view>

2. Using ng-view directive as an attribute in HTML element.

<div ng-view></div>

3. Using ng-view as a value to the class attribute in HTML element.

<div class="ng-view"></div>

Once, the view is specified, the pages will be loaded in the view when the links are clicked.

Implementation: Create an example demonstrating the concept of Angular JS Routing.

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

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

Conclusion:
I had To understand how to create Single Page Application (SPA) using Angular JS Routing

Quiz:

1. Write a note on : Routing in Angular JS.


ANS:- AngularJS is a JavaScript-based open-source front-end web framework mainly maintained
by Google and a community of individuals and corporations. It aims to simplify both the
development and the testing of single-page applications by extending HTML's syntax to express
application components clearly and concisely. AngularJS's data binding and dependency injection
eliminate much of the code you would otherwise have to write.
AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template
language and lets you extend HTML's syntax to express your application's components clearly and
concisely. AngularJS's data binding and dependency injection eliminate much of the code you
would otherwise have to write.
AngularJS makes it easy to create rich client-side applications with dynamic content. It lets you
use HTML as your template language and lets you extend HTML's syntax to express your
application's components clearly and concisely. AngularJS's data binding and dependency
injection eliminate much of the code you would otherwise have to write.

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

2. State the usefulness of ng-view directive. Explain various ways to use it


ANS:-
The `ng-view` directive in AngularJS is a very useful tool for implementing routing in single-page
applications (SPAs). It serves as a placeholder where AngularJS will render the corresponding
view/template based on the current route. Here are some of the key benefits and ways to use
the `ng-view` directive:
1. Dynamic Content Rendering: `ng-view` allows for dynamic rendering of content based on the
current route without needing to reload the entire page. This enables the creation of SPAs where
different views are loaded seamlessly as users navigate through the application.
2. Modular Architecture: With `ng-view`, you can organize your application into separate
views/templates and load them on demand. This promotes a modular architecture, making the
application easier to maintain and scale.
3. Better User Experience: By avoiding full page reloads, `ng-view` provides a smoother and faster
user experience. Users can navigate between pages quickly, and the application feels more like a
traditional desktop application.
4. SEO Friendliness: While AngularJS applications are typically single-page applications, which can
pose challenges for search engine optimization (SEO), `ng-view` allows for server-side rendering
of initial content, making the application more SEO friendly.
1. Basic Usage: Simply place the `ng-view` directive within the main HTML template where you
want the views to be rendered. AngularJS will replace the `ng-view` element with the contents of
the corresponding template based on the current route.
<div ng-view></div>
2. Nested Views: `ng-view` can also be used within nested views, allowing for hierarchical routing
and more complex application structures. This is useful for applications with multiple levels of
navigation.
<div ng-view></div>
3. Multiple Views: While `ng-view` typically renders a single view at a time, you can use AngularJS
directives like `ng-include` or custom directives to render multiple views simultaneously within
the same page.
<div ng-include="'header.html'"></div>
<div ng-view></div>
<div ng-include="'footer.html'"></div>
4. Dynamic Views: You can dynamically control which template to render in `ng-view` based on
application logic or user input by changing the route configuration programmatically using
AngularJS's `$routeProvider` or by using third-party routing libraries like `ui-router`
$routeProvider
.when('/dashboard', {
templateUrl: function() {
return isAdmin ? 'admin-dashboard.html' : 'user-dashboard.html';

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

},
controller: 'DashboardController'
})
Suggested Reference:

1. https://www.w3schools.com/angular/angular_routing.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)

3161611 Meet nikunjbhai dangi -210280116057


AWP-3161611 Meet nikunjbhai dangi 210280116026

Experiment No: 8

Aim : Study the installation of Node JS and installation of various packages in Node
JS.
Date:

Competency and Practical Skills: Node JS Environment setup

Relevant CO: CO 3

Objectives:

1. To learn installation of Node JS and the required packages in Node JS.


Theory:
• Node JS Installation
First, Node JS installation package needs to be downloaded from,
https://nodejs.org/en
After downloading the package, double click on it to install Node JS in your machine. Follow the
instructions one by one and act accordingly. This will install Node JS with some basic packages such
as, fs, os, net, dns, url, http, https, path etc. in your machine. In order to install additional packages
Node Package Manager (NPM) can be used.

• Node Package Manager


Node Package Manager allows us to install new packages, update existing packages and uninstall
existing packages. All can be done by executing following commands on Command Line Interface
provided by the operating system. Lets have a look at some most commonly used commands.

▪ To install new package locally, use, npm


install package_name

▪ To install new package globally, use, npm


install -g package_name
Here -g flag is used to install package globally

▪ To update existing package, use, npm update


package_name

▪ To uninstall already installed package, use,


npm uninstall package_name

▪ To get a list of locally installed packages, use


npm list

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

▪ To get a list of locally installed packages, use

npm list -g

Output:

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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/

References used by the students:


3161611 Meet nikunjbhai dangi -210280116026
AWP-3161611 Meet nikunjbhai dangi 210280116026

Assessment :
Node JS installation Understanding of NPM Presentation and report Total (10
marks)
process (3 marks) writing
(4 marks) (3 marks)

Node JS Detailed are Required Partial screenshots


are are given, which
installation screenshots screenshots are 01
to are nor sufficient
process
given, the 04 given, which can 03 to understand the to
which be used to process. 02
sufficient understand the
understand process
process

All the commands Sufficient are Partial commands


are discussed with
are given with commands with
Understanding or without output.
detailed 03 given 02 01
of NPM required
information and and
information
output.
output.

Presentation Unique Ordinary Weak


documentation of
and report documentation (not documentation of 01
given problem
copied from other given problem
writing 03 with proper 02 to
sources) of given without proper
formatting and 02
problem with formatting and
language
proper formatting language
and language.

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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:

Node JS concepts to be used


Node JS provides variety of functions to perform various operations on files. To use file system
related functions, file system module must be included in the current code using require( )
function. For example, var fs = require("fs");
Now using fs variable, all the functions defined in file system module can be accessed.

▪ Reading a file synchronously


To read a file synchronously readFileSync( ) function is used. It takes only one parameter,
that is the URL / Name of the file (along with the extension). To display read data in
appropriate format, you need to convert it in specific types. When a file is being read
synchronously, other processes will be blocked till the reading is done.

▪ Reading a file asynchronously


To read a file asynchronously readFile( ) function is used. It takes two parameters, first is
the URL / Name of the file (along with the extension) and second is the callback function.
To display read data in appropriate format, you need to convert it in specific types. When
a file is being read asynchronously, other processes will continue their execution in parallel
while reading is done.

▪ 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.

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

})
.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
}

const express = require('express');


const app = express();
const fs = require('fs');
const zlib = require('zlib');
const bodyParser = require('body-parser');

app.use(bodyParser.raw({ type: 'application/octet-stream' }));

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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


const fileData = fs.readFileSync(req.files.file.path, 'utf8');
res.send(fileData);
});

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


fs.readFile(req.files.file.path, 'utf8', (err, data) => {
if (err) {
res.status(500).send('Error reading file');
} else {
res.send(data);
}
});
});

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


// Implement compression logic
});

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


// Implement decompression logic
});

const PORT = process.env.PORT || 3000;


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

npm install express body-parser


Output:

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

Conclusion:

I had To understand to difference between synchronous and asynchronous processes &


the functions for compressing and decompressing files and use them.

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)

3161611 Meet nikunjbhai dangi -210280116026


AWP-3161611 Meet nikunjbhai dangi 210280116026

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

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)

3161611 Meet nikunjbhai dangi -210280116026


LDCE-028

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:

Node JS concepts to be used


To process the form, formidable module is required. It is not included in the basic Node JS
installation. Developers can install the formidable module using NPM through the following
command,

npm install formidable

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,

<form action="URL of the page" method="post" enctype="multipart/form-data">

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.

var form = new formidable.IncomingForm();

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.

3161611 Meet nikunjbhai dangi -210280116026


LDCE-028

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

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
}

const express = require('express');


const app = express();
const fs = require('fs');
const zlib = require('zlib');
const bodyParser = require('body-parser');

app.use(bodyParser.raw({ type: 'application/octet-stream' }));

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


const fileData = fs.readFileSync(req.files.file.path, 'utf8');
res.send(fileData);
});

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


fs.readFile(req.files.file.path, 'utf8', (err, data) => {
if (err) {
res.status(500).send('Error reading file');
3161611 Meet nikunjbhai dangi -210280116026
LDCE-028

} else {
res.send(data);
}
});
});

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


// Implement compression logic
});

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


// Implement decompression logic
});

const PORT = process.env.PORT || 3000;


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

npm install express body-parser

Output:

3161611 Meet nikunjbhai dangi -210280116026


LDCE-028

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

3161611 Meet nikunjbhai dangi -210280116026


LDCE-028

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

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)

3161611 Meet nikunjbhai dangi -210280116026


LDCE-028

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 :

Competency and Practical Skills: File System (fs) module of Node JS

Relevant CO : CO 3

Objectives:

1. To understand the basics of file management in Node JS.


Theory:

Node JS concepts to be used


To manage files using Node JS applications, file system (fs) module is required. It provides various
functions to manage the files.
Following functions will be used to manage files using Node JS :

1. readFile( ) : It is used to read a file.

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.

5. unlink( ) : It is used to delete a file.

6. rename( ) : It is used to rename an existing file.

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 createFile(filename, content) {


3161611 Meet nikunjbhai dangi -210280116026
LDCE-028

fs.writeFile(filename, content, (err) => {


if (err) throw err;
console.log(`File '${filename}' created successfully.`);
});
}

function readFile(filename) {
fs.readFile(filename, 'utf8', (err, data) => {
if (err) throw err;
console.log(`Content of '${filename}':`);
console.log(data);
});
}

function writeToFile(filename, content) {


fs.appendFile(filename, content, 'utf8', (err) => {
if (err) throw err;
console.log(`Content appended to '${filename}' successfully.`);
});
}

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

3161611 Meet nikunjbhai dangi -210280116026


LDCE-028

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:

3161611 Meet nikunjbhai dangi -210280116026


LDCE-028

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 server = http.createServer((req, res) => {


// Parse the URL to get the directory path
const url = new URL(req.url, `http://${req.headers.host}`);
const dirPath = url.pathname;

// Get the absolute path of the directory


const absoluteDirPath = path.join(__dirname, dirPath);

// Check if the directory exists


fs.access(absoluteDirPath, fs.constants.F_OK, (err) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Directory not found');
} else {
// Read the contents of the directory
fs.readdir(absoluteDirPath, (err, files) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
// Send the list of files as HTML response
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<h1>Files in Directory</h1>');
res.write('<ul>');
files.forEach((file) => {
res.write(`<li>${file}</li>`);
});
res.write('</ul>');
res.end();
3161611 Meet nikunjbhai dangi -210280116026
LDCE-028

}
});
}
});
});

const PORT = process.env.PORT || 3000;


server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
2. Create Node JS application that will allow a user to create new files and rename existing
files using the proper interface
ANS:- const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

function createFile(filename, content) {


fs.writeFile(filename, content, (err) => {
if (err) {
console.error('Error creating file:', err);
} else {
console.log(`File '${filename}' created successfully.`);
}
rl.close();
});
}

function renameFile(oldFilename, newFilename) {


fs.rename(oldFilename, newFilename, (err) => {
if (err) {
console.error('Error renaming file:', err);
} else {
console.log(`File '${oldFilename}' renamed to '${newFilename}' successfully.`);
}
rl.close();
});
}

3161611 Meet nikunjbhai dangi -210280116026


LDCE-028

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

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)

3161611 Meet nikunjbhai dangi -210280116026


LDCE-028

EXPERIMENT:-12

AIM:-Study MongoDB environment setup and write Node JS code to perform


insertion operation in Mongo DB.
Date :

Competency and Practical Skills: Operations on MongoDB Database, Node JS code for insertion in
MongoDB Database.

Relevant CO : CO 3, CO 4

Objectives:

1. To understand the installation of MongoDB.

2. To understand how to interact with MongoDB Database through Node JS code.


Theory:

• 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.

• Node JS concepts to be used


▪ After successful installation of MongoDB, services of MongoDB will be accessible through
MongoClient object of mongodb package in Node JS.

▪ connect( ) function of MongoClient will allow a user to create a database, if database


doesn’t exists.

▪ All the documents of a MongoDB database are maintained in a collection, a collection is


similar to a table in relational databases.

▪ To create a collection, createCollection( ) function of Database object can be used.

▪ And collection( ) function of Database object can be used to access the collection.

3161611 Meet nikunjbhai dangi -210280116026


LDCE-028

▪ 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.

▪ To insert a single document insertOne( ) function is used.

▪ In case of insertion of multiple documents, insertMany( ) function can be used.

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

async function insertDocuments() {


try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('documents');
const result = await collection.insertMany([
{ name: 'Narendra Modi', age: 73 },
{ name: 'Elon Musk', age: 53 }
]);
console.log(`${result.insertedCount} documents inserted successfully.`);
} catch (error) {
console.error('Error inserting documents:', error);
} finally {
await client.close();
}
}

insertDocuments().catch(console.error);

Output:

Conclusion:
I had To understand the installation of MongoDB & how to interact with MongoDB Database
through Node JS code.

3161611 Meet nikunjbhai dangi -210280116026


LDCE-028

Practical Quiz:

1. Differentiate between Relational Database and Document Database. OR Differentiate


between SQL Database and No SQL Database.

1. ANS;- Data Model:

• Relational Databases (SQL):

• Relational databases follow a tabular data model where data is organized


into tables consisting of rows and columns.

• Each table represents an entity, and each row represents a record or


instance of that entity.

• Relationships between tables are established using foreign key constraints.

• Document Databases (NoSQL):

• Document databases follow a flexible schema data model where data is


stored in documents, typically in JSON or BSON format.

• Each document is a self-contained unit that contains key-value pairs or


nested structures.

• Documents within a collection do not have to have the same structure,


allowing for schema flexibility and easier handling of nested data.

2. Schema:

• Relational Databases (SQL):

• Relational databases have a rigid schema where the structure of the


database, including tables, columns, and data types, is defined upfront.

• Any changes to the schema often require altering the database schema,
which can be complex and may impact existing data.

• Document Databases (NoSQL):

• Document databases have a dynamic schema where documents within a


collection can have different structures.

• There is typically no predefined schema, allowing for more flexibility in data


representation and easier adaptation to changing requirements.

3. Scalability:

• Relational Databases (SQL):

• Relational databases are traditionally scaled vertically by increasing the


resources (CPU, memory, etc.) of the server.

3161611 Meet nikunjbhai dangi -210280116026


LDCE-028

• Scaling out (horizontally) can be challenging and often requires complex


sharding techniques.

• Document Databases (NoSQL):

• Document databases are designed for horizontal scalability, making it easier


to scale out by distributing data across multiple servers or nodes.

• They can handle large volumes of data and high throughput by adding more
servers to the cluster.

4. Query Language:

• Relational Databases (SQL):

• SQL (Structured Query Language) is the standard query language for


relational databases.

• SQL provides a powerful set of declarative commands for querying and


manipulating data, including SELECT, INSERT, UPDATE, DELETE, and JOIN
operations.

• Document Databases (NoSQL):

• 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.

5. Transactions and ACID Properties:

• Relational Databases (SQL):

• Relational databases support ACID (Atomicity, Consistency, Isolation,


Durability) properties and transactions, ensuring data integrity and
reliability.

• Transactions allow multiple operations to be grouped together and executed


as a single unit, ensuring that either all operations succeed or none of them
are applied.

• Document Databases (NoSQL):

• Document databases may offer varying degrees of support for transactions


and ACID properties, but they often prioritize scalability and performance
over strict consistency guarantees.

• Some document databases offer eventual consistency models where data


consistency is eventually achieved after a certain period of time.

3161611 Meet nikunjbhai dangi -210280116026


LDCE-028

2. Discuss various methods available in Node JS to perform various operations on MongoDB.


1. ANS:- Connecting to MongoDB:
• Use mongoose.connect() method to connect to MongoDB. You can pass the
connection URI as an argument to this method.
2. Defining Schemas:
• Use mongoose.Schema() method to define the structure of your documents. Each
schema maps to a MongoDB collection and defines the shape of documents within
that collection.
3. Defining Models:
• Use mongoose.model() method to create a model based on the defined schema.
Models provide an interface to interact with MongoDB collections.
4. Creating Documents:
• Use the Model.create() method to create new documents in the database. You can
pass an object representing the document as an argument to this method.
5. Reading Documents:
• Use various querying methods provided by mongoose to read documents from the
database. For example:
• Use Model.find() to find documents that match a given query criteria.
• Use Model.findOne() to find a single document that matches a given query
criteria.
• Use Model.findById() to find a document by its _id field.
6. Updating Documents:
• Use the Model.updateOne(), Model.updateMany(), or
Model.findOneAndUpdate() methods to update documents in the database. You
can specify the update criteria and the new values to be set.
7. Deleting Documents:
• Use the Model.deleteOne(), Model.deleteMany(), or Model.findOneAndDelete()
methods to delete documents from the database. You can specify the delete criteria
to remove specific documents.
8. Aggregation:
• Use Model.aggregate() method to perform aggregation operations like grouping,
filtering, and sorting on documents in the collection.
9. Transactions:

3161611 Meet nikunjbhai dangi -210280116026


LDCE-028

• Use Session.startTransaction() method to start a transaction and


Session.commitTransaction() method to commit the transaction. You can use
transactions to perform multiple operations as a single unit of work.
10. Error Handling:
• Handle errors using try-catch blocks or .catch() method on promises returned by
mongoose methods. This ensures graceful error handling and prevents crashes.
Suggested Reference:

1. https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-windows/

2. https://www.w3schools.com/nodejs/nodejs_mongodb_insert.asp

References used by the students

Assessment :
Understanding of Implementation of Presentation and Total (10
Problem Problem report writing (3 marks)
(3 marks) (4 marks) marks)

3161611 Meet nikunjbhai dangi -210280116026


EXPERMINET:-13
AIM:-Write Node JS code to perform deletion operation from Mongo DB.
Date :

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:

Node JS concepts to be used


▪ Services of MongoDB will be accessible through MongoClient object of mongodb package
in Node JS.

▪ 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.

▪ The use deleteOne( ) function of collection to delete single document.

▪ You can use deleteMany( ) function of collection to delete multiple documents


simultaneously.

Implementation : Write Node JS code to perform deletion operation from Mongo DB.

const mongoose = require('mongoose');


// MongoDB connection URI
const mongoURI = 'mongodb://localhost:27017/mydatabase';

// Define a schema for the data


const Schema = mongoose.Schema;
const dataSchema = new Schema({
name: String,
age: Number,
email: String
});

// Define a model based on the schema


const DataModel = mongoose.model('Data', dataSchema);

3161611 Meet nikunjbhai dangi -210280116026


// Connect to MongoDB
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true });

// Delete documents that match a given condition


DataModel.deleteMany({ age: { $gte: 30 } })
.then((result) => {
console.log(`Deleted ${result.deletedCount} documents`);
})
.catch((err) => {
console.error('Error deleting documents:', err);
});
Output:

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

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)

3161611 Meet nikunjbhai dangi -210280116026


EXPERMINET:-14

AIM:-Write Node JS code to perform selection and updation operation to select


and update specific document in Mongo DB.
Date :

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:

Node JS concepts to be used


▪ Services of MongoDB will be accessible through MongoClient object of mongodb package
in Node JS.

▪ 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.

▪ Using find( ) method of the collection object, document can be searched.

▪ If the document is found then it’s details can be printed / used as per need.

▪ For updating documents, use updateOne( ) function of collection to update a single


document and use updateMany( ) function of collection, to update multiple documents.

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

3161611 Meet nikunjbhai dangi -210280116026


const db = client.db(dbName);
const collection = db.collection(collectionName);
const filter = { _id: new ObjectId(documentId) };
const document = await collection.findOne(filter);
if (!document) {
console.log('Document not found');
return;
}
const result = await collection.updateOne(filter, update);
console.log(`${result.modifiedCount} document(s) updated`);
} catch (error) {
console.error('Error occurred:', error);
} finally {
if (client) {
await client.close();
}
}
}
const documentId = '6618edd216bf9337f39ee9b3';
const update = { $set:{name: 'Viral', age: 21} };
selectAndUpdateDocument('documents', documentId, update);
Output:

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)

3161611 Meet nikunjbhai dangi -210280116026


EXPERIMENT:-15

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

const app = express();


const PORT = process.env.PORT || 3000;

// MongoDB connection URI


const mongoURI = 'mongodb://localhost:27017/library';

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

3161611 Meet nikunjbhai dangi -210280116026


// Routes
app.post('/api/books', async (req, res) => {
try {
const { title, author } = req.body;
const book = new Book({ title, author, available: true });
await book.save();
res.status(201).json(book);
} catch (err) {
console.error('Error adding book:', err);
res.status(500).json({ error: 'Failed to add book' });
}
});

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


try {
const { title } = req.query;
const books = await Book.find({ title });
res.json(books);
} catch (err) {
console.error('Error searching books:', err);
res.status(500).json({ error: 'Failed to search books' });
}
});

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

<!-- frontend/index.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Library App</title>
</head>
<body>
<div id="app">
<router-view></router-view>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="app.js"></script>
</body>

3161611 Meet nikunjbhai dangi -210280116026


</html>

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

3161611 Meet nikunjbhai dangi -210280116026


<button @click="searchBooks">Search</button>
<ul v-if="books.length">
<li v-for="book in books" :key="book._id">{{ book.title }} by {{ book.author }} ({{
book.available ? 'Available' : 'Not Available' }})</li>
</ul>
<p v-else>No books found</p>
</div>
`,
data() {
return {
query: '',
books: []
};
},
methods: {
async searchBooks() {
try {
const response = await fetch(`/api/books?title=${this.query}`);
this.books = await response.json();
} catch (err) {
console.error('Error searching books:', err);
}
}
}
};

const routes = [
{ path: '/add-book', component: AddBook },
{ path: '/search-books', component: SearchBooks }
];

const router = new VueRouter({ routes });

new Vue({ router }).$mount('#app');

3161611 Meet nikunjbhai dangi -210280116026


Output:

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)

3161611 Meet nikunjbhai dangi -210280116026

You might also like