5.AWP Labmanual New

Download as pdf or txt
Download as pdf or txt
You are on page 1of 93

Ahmedabad Institute of Technology

Computer Engineering Department

Advanced Web Programming(3161611)

Laboratory Manual

Year: 2022-2023

Prepared By: - Prof. Darshana. H. Patel.

Department Vision:
”To produce technically sound and ethically responsible Computer Engineers to the society
by providing Quality Education.”

Department Mission:
To provide healthy Learning Environment based on current and future Industrial demands
To promote curricular, co-curricular and extra-curricular activities for overall personality
development of the students.
To build technically and ethically strong mind having real life problem solving capabilities.
To provide platform for Effective Teaching Learning.
INDEX

Sr. Page No.


No Experiment Date Marks Signature
From To
.

1. Introduction to
HTML,CSS,JavaScript, BootStap
2.ExExpressions in AngularJS

3. Angular JS Forms and Validations


4. Creating single page website
using AngularJS
5. Node JS Concept of Callbacks
6. Node JS File System
7. Networking with Node Node JS
8. Node JS Web Module
9. Connect Node JS with MongoDB
10. Operations on data in MongoDB

Page 2 of 93
EXPERIMENT NO: 1 DATE: / /

TITLE: Introduction to HTML,CSS,JavaScript,BootStap.

OBJECTIVES: On completion of this experiment students will be able to…


➢ know the concept of HTML,CSS,JavaScript,BootStap.
➢ Create a simple Portfolio which shows all your skills.

THEORY:
What is HTML,CSS,JavaScript,Bootstrap:

Bootstrap is the most popular and powerful front-end (HTML, CSS, and JavaScript)
framework for faster and easier responsive web development.
Bootstrap is a powerful front-end framework for faster and easier web development. It
includes HTML and CSS based design templates for creating common user interface
components like forms, buttons, navigations, dropdowns, alerts, modals, tabs,
accordions, carousels, tooltips, and so on.
Bootstrap gives you the ability to create flexible and responsive web layouts with much
less effort.
Bootstrap was originally created by a designer and a developer at Twitter in mid-2010.
Before being an open-sourced framework, Bootstrap was known as Twitter Blueprint.

What You Can Do with Bootstrap

There are a lot more things you can do with Bootstrap.


● You can easily create responsive websites.
● You can quickly create a multi-column layout with predefined classes.
● You can quickly create different types of form layouts.
● You can quickly create different variations of navigation bars.
● You can easily create components like accordions, modals, etc. without writing
any JS code.
● You can easily create dynamic tabs to manage a large amount of content.
● You can easily create tooltips and popovers to show hint text.
● You can easily create a carousel or image slider to showcase your content.
● You can quickly create different types of alert boxes.

Advantages of Using Bootstrap

If you have had some experience with any front-end framework, you might be
wondering what makes Bootstrap so special. Here are some advantages why one should
opt for Bootstrap framework:

Page 3 of 93
● Save lots of time — You can save lots of time and efforts using the Bootstrap
predefined design templates and classes and concentrate on other
development work.
● Responsive features — Using Bootstrap you can easily create responsive
websites that appear more appropriately on different devices and screen
resolutions without any change in markup.
● Consistent design — All Bootstrap components share the same design templates
and styles through a central library, so the design and layout of your web pages
will be consistent.
● Easy to use — Bootstrap is very easy to use. Anybody with the basic working
knowledge of HTML, CSS and JavaScript can start development with Bootstrap.
● Compatible with browsers — Bootstrap is created with modern web browsers in
mind and it is compatible with all modern browsers such as Chrome, Firefox,
Safari, Internet Explorer, etc.
● Open Source — And the best part is, it is completely free to download and use.

Creating Your First Web Page with Bootstrap

Step 1: Creating a Basic HTML file

Open up your favorite code editor and create a new HTML file. Start with an empty
window and type the following code and save it as "basic.html" on your desktop.
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-


to-fit=no">

<title>Basic HTML File</title>

</head>

<body>

<h1>Hello, world!</h1>

Page 4 of 93
</body>

</html>

Step 2: Making this HTML File a Bootstrap Template

In order to make this plain HTML file a Bootstrap template, just include the Bootstrap
CSS and JS files as well as required jQuery and Popper.js using their CDN links.
You should include JavaScript files at the bottom of the page, right before the closing
</body> tag to improve the performance of your web pages, as shown in the following
example:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-


to-fit=no">

<title>Basic Bootstrap Template</title>

<!-- Bootstrap CSS file -->

<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.c
ss">

</head>

<body>

<h1>Hello, world!</h1>

<!-- JS files: jQuery first, then Popper.js, then Bootstrap JS -->

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

Page 5 of 93
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
></script>

<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
></script>

</body>

</html>

And we're all set! After adding the Bootstrap's CSS and JS files and the required jQuery
and Popper.js library, we can begin to develop any site or application with the
Bootstrap framework.
The attributes integrity and crossorigin have been added to CDN links to implement
Subresource Integrity (SRI). It is a security feature that enables you to mitigate the risk
of attacks originating from compromised CDNs, by ensuring that the files your website
fetches (from a CDN or anywhere) have been delivered without unexpected or
malicious modifications. It works by allowing you to provide a cryptographic hash that
a fetched file must match.

Step 3: Saving and Viewing the File

Now save the file on your desktop as "bootstrap-template.html".


To open this file in a web browser, navigate to it, then right click on it, and select your
favorite web browser. Alternatively, you can open your browser and drag this file to it.
EXERCISE:

1.Create Custom components using bootstrap


2. Create Navbars using bootstrap
3.Create Form using bootstrap
4. Create Grid using bootstrap
5. Create bootstrap themes
6. Create student records using CSS and bootstrap.
7. Create your portfolio using HTML,CSS,JavaScript and Bootstrap

Page 6 of 93
EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________

Page 7 of 93
EXPERIMENT NO: 2 DATE: / /

TITLE: Expressions in AngularJS

OBJECTIVES: On completion of this experiment students will be able to…


➢ know the concept of routers and navigation BootStap.

THEORY:

What is AngularJS

AngularJS is a JavaScript framework. It can be added to an HTML page with a <script>


tag.

AngularJS extends HTML attributes with Directives, and binds data to HTML with
Expressions.

AngularJS is a JavaScript framework written in JavaScript.

AngularJS is distributed as a JavaScript file, and can be added to a web page with a
script tag:

<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

AngularJS Extends HTML

AngularJS extends HTML with ng-directives.

The ng-app directive defines an AngularJS application.

The ng-model directive binds the value of HTML controls (input, select, textarea) to
application data.

The ng-bind directive binds application data to the HTML view.

<!DOCTYPE html>

<html>

<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

Page 8 of 93
<body>

<div ng-app="">

<p>Name: <input type="text" ng-model="name"></p>

<p ng-bind="name"></p>

</div>

</body>

</html>

AngularJS starts automatically when the web page has loaded.

The ng-app directive tells AngularJS that the <div> element is the "owner" of an
AngularJS application.

The ng-model directive binds the value of the input field to the application variable
name.

The ng-bind directive binds the content of the <p> element to the application variable
name.

AngularJS Expressions

AngularJS expressions can be written inside double braces: {{ expression }}.

AngularJS expressions can also be written inside a directive: ng-bind="expression".

AngularJS will resolve the expression, and return the result exactly where the
expression is written.

AngularJS expressions are much like JavaScript expressions: They can contain literals,
operators, and variables.

Page 9 of 93
Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}

<!DOCTYPE html>

<html>

<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="">

<p>My first expression: {{ 5 + 5 }}</p>

</div>

</body>

</html>

EXERCISE:

1.Create Angular JS Application using expression


1.Create Navigation Menu
2. Create inline editor
3.Create Instant Search

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________

Page 10 of 93
EXPERIMENT NO: 3 DATE: / /

TITLE: Angular JS Forms and Validations.

OBJECTIVES: On completion of this experiment students will be able to…


➢ know the concept of HTML,CSS,JavaScript,BootStap.
➢ Create a simple Portfolio which shows all your skills.

THEORY:
Forms in AngularJS provide data-binding and validation of input controls.
Input Controls

Input controls are the HTML input elements:

● input elements
● select elements
● button elements
● textarea elements

Data-Binding

Input controls provide data-binding by using the ng-model directive.

<input type="text" ng-model="firstname">

The application does now have a property named firstname.

The ng-model directive binds the input controller to the rest of your application.

The property firstname, can be referred to in a controller:

<!DOCTYPE html>
<html lang="en">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">


<form>
First Name: <input type="text" ng-model="firstname">
</form>
</div>

Page 11 of 93
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.firstname = "John";
});
</script>

</body>
</html>

AngularJS can validate input data.


Form Validation

AngularJS offers client-side form validation.

AngularJS monitors the state of the form and input fields (input, textarea, select), and
lets you notify the user about the current state.

AngularJS also holds information about whether they have been touched, or modified,
or not.

You can use standard HTML5 attributes to validate input, or you can make your own
validation functions.

Required

Use the HTML5 attribute required to specify that the input field must be filled out:

<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="">

<p>Try writing in the input field:</p>

<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>

<p>The input's valid state is:</p>


<h1>{{myForm.myInput.$valid}}</h1>

</body>
</html>

Page 12 of 93
Custom Validation

To create your own validation function is a bit more tricky; You have to add a new
directive to your application, and deal with the validation inside a function with certain
specified arguments.
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">

<p>Try writing in the input field:</p>

<form name="myForm">
<input name="myInput" ng-model="myInput" required my-directive>
</form>

<p>The input's valid state is:</p>


<h1>{{myForm.myInput.$valid}}</h1>

<script>
var app = angular.module('myApp', []);
app.directive('myDirective', function() {
return {
require: 'ngModel',
link: function(scope, element, attr, mCtrl) {
function myValidation(value) {
if (value.indexOf("e") > -1) {
mCtrl.$setValidity('charE', true);
} else {
mCtrl.$setValidity('charE', false);
}
return value;
}
mCtrl.$parsers.push(myValidation);
}
};
});
</script>
<p>The input field must contain the character "e" to be considered valid.</p>

</body>
</html>

Page 13 of 93
EXERCISE:

1.Create student information form and apply validation

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________

Page 14 of 93
EXPERIMENT NO: 4 DATE: / /

TITLE: Creating a single page website using AngularJS.

OBJECTIVES: On completion of this experiment students will be able to…


➢ know the concept of SPA.

THEORY:
What is SPA (Single page application) in AngularJS?
Traditionally, applications were Multi-Page Application (MPA) where with every click a
new page would be loaded from the server. This was not only time consuming but also
increased the server load and made the website slower. AngularJS is a JavaScript-based
front-end web framework based on bidirectional UI data binding and is used to design
Single Page Applications. Single Page Applications are web applications that load a
single HTML page and only a part of the page instead of the entire page gets updated
with every click of the mouse. The page does not reload or transfer control to another
page during the process. This ensures high performance and loading pages faster. Most
modern applications use the concept of SPA. In the SPA, the whole data is sent to the
client from the server at the beginning. As the client clicks certain parts on the webpage,
only the required part of the information is fetched from the server and the page is
rewritten dynamically. This results in a lesser load on the server and is cost-efficient.
SPAs use AJAX and HTML5 to create a fluid and responsive Web applications and most
of the work happens on the client-side. Popular applications such as Facebook, Gmail,
Twitter, Google Drive, Netflix, and many more are examples of SPA.
Advantages:
● Team collaboration
Single-page applications are excellent when more than one developer is
working on the same project. It allows backend developers to focus on the
API, while the frontend developers can focus on creating the user interface
based on the backend API.
● Caching
The application sends a single request to the server and stores all the
received information in the cache. This proves beneficial when the client has
poor network connectivity.

Page 15 of 93
● Fast and responsive
As only parts of the pages are loaded dynamically, it improves the website’s
speed.
● Debugging is easier
Debugging single page applications with chrome is easier since such
applications are developed using like AngularJS Batarang and React
developer tools.
● Linear user experience
Browsing or navigating through the website is easy.

Disadvantages:
● SEO optimization
SPAs provide poor SEO optimization. This is because single-page applications
operate on JavaScript and load data at once from the server. The URL does
not change and different pages do not have a unique URL. Hence it is hard for
the search engines to index the SPA website as opposed to traditional server-
rendered pages.
● Browser history
A SPA does not save the users’ transition of states within the website. A
browser saves the previous pages only, not the state transition. Thus when
users click the back button, they are not redirected to the previous state of
the website. To solve this problem, developers can equip their SPA
frameworks with the HTML5 History API.
● Security issues
Single-page apps are less immune to cross-site scripting (XSS) and since no
new pages are loaded, hackers can easily gain access to the website and
inject new scripts on the client-side.
● Memory Consumption
Since the SPA can run for a long time, sometimes hours at a time, one needs

Page 16 of 93
to make sure the application does not consume more memory than it needs.
Else, users with low memory devices may face serious performance issues.
● Disabled Javascript
Developers need to chalk out ideas for users to access the information on the
website for browsers that have Javascript disabled.

When to use SPA?

SPAs are good when the volume of data is small and the website that needs a dynamic
platform. It is also a good option for mobile applications. But businesses that depend
largely on search engine optimizations such as e-commerce applications must avoid
single-page applications and opt for MPAs.

<!DOCTYPE html>
<!--ng-app directive tells AngularJS that myApp
is the root element of the application -->
<html ng-app="myApp">
<head>
<!--import the angularjs libraries-->
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js">
</script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.min.js">
</script>
</head>
<body>
<!--hg-template indicates the pages
that get loaded as per requirement-->
<script type="text/ng-template"
id="first.html">
<h1>First Page</h1>
<h2 style="color:green">
Welcome to AIT
</h2>
<h3>{{message}}</h3>
</script>
<script type="text/ng-template"
id="second.html">

Page 17 of 93
<h1>Second Page</h1>
<h2 style="color:green">
Start Learning With GFG
</h2>
<h3>{{message}}</h3>
</script>
<script type="text/ng-template"
id="third.html">
<h1>Third Page</h1>
<h2 style="color:green">
Know about us
</h2>
<h3>{{message}}</h3>
</script>
<!--hyperlinks to load different
pages dynamically-->
<a href="#/">First</a>
<a href="#/second">Second</a>
<a href="#/third">Third</a>
<!--ng-view includes the rendered template of
the current route into the main page-->
<div ng-view></div>
<script>
var app = angular.module('myApp', []);
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider

.when('/', {
templateUrl : 'first.html',
controller : 'FirstController'
})

.when('/second', {
templateUrl : 'second.html',
controller : 'SecondController'
})

.when('/third', {
templateUrl : 'third.html',
controller : 'ThirdController'
})

.otherwise({redirectTo: '/'});
});

Page 18 of 93
<!-- controller is a JS function that maintains
application data and behavior using $scope object -->
<!--properties and methods can be attached to the
$scope object inside a controller function-->

app.controller('FirstController', function($scope) {
$scope.message = 'Hello from FirstController';
});

app.controller('SecondController', function($scope) {
$scope.message = 'Hello from SecondController';
});

app.controller('ThirdController', function($scope) {
$scope.message = 'Hello from ThirdController';
});
</script>
</body>
</html>

EXERCISE:

1.Create Single Page Application in Angular JS.

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________

Page 19 of 93
EXPERIMENT NO: 5 DATE: / /

TITLE: Node JS Concept.

OBJECTIVES: On completion of this experiment students will be able to…


➢ know the concept of Node JS.

THEORY:

● Node.js is an open source server environment


● Node.js is free
● Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
● Node.js uses JavaScript on the server

A common task for a web server can be to open a file on the server and return the content to the
client.

Here is how PHP or ASP handles a file request:

1. Sends the task to the computer's file system.


2. Waits while the file system opens and reads the file.
3. Returns the content to the client.
4. Ready to handle the next request.

Here is how Node.js handles a file request:

1. Sends the task to the computer's file system.


2. Ready to handle the next request.
3. When the file system has opened and read the file, the server returns the content to
the client.

Node.js eliminates the waiting, and simply continues with the next request.

Node.js runs single-threaded, non-blocking, asynchronously programming, which is very memory


efficient.

What Can Node.js Do?

● Node.js can generate dynamic page content


● Node.js can create, open, read, write, delete, and close files on the server
● Node.js can collect form data
● Node.js can add, delete, modify data in your database

Page 20 of 93
What is a Node.js File?

● Node.js files contain tasks that will be executed on certain events


● A typical event is someone trying to access a port on the server
● Node.js files must be initiated on the server before having any effect
● Node.js files have extension ".js"

Node.js Modules
What is a Module in Node.js?

Consider modules to be the same as JavaScript libraries.

A set of functions you want to include in your application.

Built-in Modules

Node.js has a set of built-in modules which you can use without any further installation.

Node.js has a set of built-in modules which you can use without any further installation.

Here is a list of the built-in modules of Node.js version 6.10.3:

Module Description

assert Provides a set of assertion tests

buffer To handle binary data

child_process To run a child process

cluster To split a single Node process into multiple processes

Page 21 of 93
crypto To handle OpenSSL cryptographic functions

dgram Provides implementation of UDP datagram sockets

dns To do DNS lookups and name resolution functions

domain Deprecated. To handle unhandled errors

events To handle events

fs To handle the file system

http To make Node.js act as an HTTP server

https To make Node.js act as an HTTPS server.

net To create servers and clients

os Provides information about the operation system

path To handle file paths

Page 22 of 93
punycode Deprecated. A character encoding scheme

querystring To handle URL query strings

readline To handle readable streams one line at the time

stream To handle streaming data

string_decoder To decode buffer objects into strings

timers To execute a function after a given number of milliseconds

tls To implement TLS and SSL protocols

tty Provides classes used by a text terminal

url To parse URL strings

util To access utility functions

v8 To access information about V8 (the JavaScript engine)

Page 23 of 93
vm To compile JavaScript code in a virtual machine

zlib To compress or decompress files

include Modules

To include a module, use the require() function with the name of the module:

var http = require('http');

Now your application has access to the HTTP module, and is able to create a server:

http.createServer(function (req, res) {

res.writeHead(200, {'Content-Type': 'text/html'});

res.end('Hello World!');

}).listen(8080);

Create Your Own Modules

You can create your own modules, and easily include them in your applications.

The following example creates a module that returns a date and time object:

Example
Create a module that returns the current date and time:

exports.myDateTime = function () {

return Date();

};

Use the exports keyword to make properties and methods available outside the module
file.

Page 24 of 93
Save the code above in a file called "myfirstmodule.js"

Include Your Own Module

Now you can include and use the module in any of your Node.js files.

App.js

var http = require('http');


var dt = require('./myfirstmodule');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time is currently: " + dt.myDateTime());
res.end();
}).listen(8080);

Notice that we use ./ to locate the module, that means that the module is located in the
same folder as the Node.js file.

Save the code above in a file called "demo_module.js", and initiate the file:

Initiate demo_module.js:

C:\Users\Your Name>node demo_module.js

If you have followed the same steps on your computer, you will see the same result as
the example: http://localhost:8080

EXERCISE:

1.Create Node.JS callback Application.

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________

Page 25 of 93
EXPERIMENT NO: 6 DATE: / /

TITLE: Node JS File System

OBJECTIVES: On completion of this experiment students will be able to…


➢ know the concept of File System and related operations

THEORY:

Node implements File I/O using simple wrappers around standard

POSIX functions. The Node File System (fs) module can be imported

using the following syntax −

var fs = require("fs")

Synchronous vs Asynchronous
Every method in the fs module has synchronous as well as asynchronous forms.
Asynchronous methods take the last parameter as the completion function callback
and the first parameter of the callback function as error. It is better to use an
asynchronous method instead of a synchronous method, as the former never blocks a
program during its execution, whereas the second one does.

Example

Create a text file named input.txt with the following content −

Ahmedabad Institute of technology is giving learning content

to teach the world in simple and easy way!!!!!

------------------------------------------------------------------------------------------------------

Let us create a js file named main.js with the following code −

var fs = require("fs");

Page 26 of 93
// Asynchronous read

fs.readFile('input.txt', function (err, data) {

if (err) {

return console.error(err);

console.log("Asynchronous read: " + data.toString());

});

// Synchronous read

var data = fs.readFileSync('input.txt');

console.log("Synchronous read: " + data.toString());

console.log("Program Ended");

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Synchronous read:Ahmedabad Institute of technology is giving learning content

to teach the world in simple and easy way!!!!!

Program Ended

Asynchronous read: Ahmedabad Institute of technology is giving learning content

to teach the world in simple and easy way!!!!!

Page 27 of 93
● Open a File

Syntax

Following is the syntax of the method to open a file in asynchronous

mode −

fs.open(path, flags[, mode], callback)

Parameters

Here is the description of the parameters used −

● path − This is the string having file name including path.

● flags − Flags indicate the behavior of the file to be opened. All

possible values have been mentioned below.

● mode − It sets the file mode (permission and sticky bits), but only if

the file was created. It defaults to 0666, readable and writeable.

● callback − This is the callback function which gets two arguments

(err, fd).

Flags

Flags for read/write operations are −

Sr.No. Flag & Description

r :Open file for reading. An exception occurs if the file does not exist.
1

r+:Open file for reading and writing. An exception occurs if the file does not
2

Page 28 of 93
exist.

rs:Open file for reading in synchronous mode.


3

rs+:Open file for reading and writing, asking the OS to open it synchronously.
4
See notes for 'rs' about using this with caution.

w:Open file for writing. The file is created (if it does not exist) or truncated (if it
5
exists).

wx:Like 'w' but fails if the path exists.


6

w+:Open file for reading and writing. The file is created (if it does not exist) or
7
truncated (if it exists).

wx+:Like 'w+' but fails if path exists.


8

a:Open file for appending. The file is created if it does not exist.
9

Page 29 of 93
ax:Like 'a' but fails if the path exists.
10

a+:Open file for reading and appending. The file is created if it does not exist.
11

ax+:Like 'a+' but fails if the the path exists.


12

Example
Let us create a js file named main.js having the following code to open a file input.txt
for reading and writing.

var fs = require("fs");

// Asynchronous - Opening File

console.log("Going to open file!");

fs.open('input.txt', 'r+', function(err, fd) {

if (err) {

return console.error(err);

console.log("File opened successfully!");

});

Now run the main.js to see the result −

Page 30 of 93
$ node main.js

Verify the Output.

Going to open file!

File opened successfully!

--------------------------------------------------------------------------------------------------------

Get File Information

Syntax

Following is the syntax of the method to get the information about a file

fs.stat(path, callback)

Parameters

Here is the description of the parameters used −

● path − This is the string having file name including path.

● callback − This is the callback function which gets two arguments

(err, stats) where stats is an object of fs.Stats type which is printed

below in the example.

Apart from the important attributes which are printed below in the example, there are
several useful methods available in fs.Stats class which can be used to check file type.
These methods are given in the following table.

Page 31 of 93
Sr.No. Method & Description

stats.isFile()
1

Returns true if file type of a simple file.

stats.isDirectory()
2

Returns true if file type of a directory.

stats.isBlockDevice()
3

Returns true if file type of a block device.

stats.isCharacterDevice()
4

Returns true if file type of a character device.

stats.isSymbolicLink()
5

Returns true if file type of a symbolic link.

stats.isFIFO()
6

Page 32 of 93
Returns true if file type of a FIFO.

stats.isSocket()
7

Returns true if file type of a socket.

Example

Let us create a js file named main.js with the following code −

var fs = require("fs");

console.log("Going to get file info!");

fs.stat('input.txt', function (err, stats) {

if (err) {

return console.error(err);

console.log(stats);

console.log("Got file info successfully!");

// Check file type

console.log("isFile ? " + stats.isFile());

console.log("isDirectory ? " + stats.isDirectory());

});

Page 33 of 93
Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to get file info!

dev: 1792,

mode: 33188,

nlink: 1,

uid: 48,

gid: 48,

rdev: 0,

blksize: 4096,

ino: 4318127,

size: 97,

blocks: 8,

atime: Sun Mar 22 2015 13:40:00 GMT-0500 (CDT),

mtime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT),

ctime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT)

Page 34 of 93
Got file info successfully!

isFile ? true

isDirectory ? false

--------------------------------------------------------------------------------------------------------

Writing a File

Syntax

Following is the syntax of one of the methods to write into a file −

fs.writeFile(filename, data[, options], callback)

This method will over-write the file if the file already exists. If you want to write into
an existing file then you should use another method available.

Parameters

Here is the description of the parameters used −

● path − This is the string having the file name including path.

● data − This is the String or Buffer to be written into the file.

● options − The third parameter is an object which will hold

{encoding, mode, flag}. By default. encoding is utf8, mode is octal

value 0666. and flag is 'w'

● callback − This is the callback function which gets a single

parameter err that returns an error in case of any writing error.

Example

Let us create a js file named main.js having the following code −

Page 35 of 93
var fs = require("fs");

console.log("Going to write into existing file");

fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) {

if (err) {

return console.error(err);

console.log("Data written successfully!");

console.log("Let's read newly written data");

fs.readFile('input.txt', function (err, data) {

if (err) {

return console.error(err);

console.log("Asynchronous read: " + data.toString());

});

});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to write into existing file

Page 36 of 93
Data written successfully!

Let's read newly written data

Asynchronous read: Simply Easy Learning!

--------------------------------------------------------------------------------------------------------

Reading a File

Syntax

Following is the syntax of one of the methods to read from a file −

fs.read(fd, buffer, offset, length, position, callback)

This method will use file descriptor to read the file. If you want to read the file directly
using the file name, then you should use another method available.

Parameters

Here is the description of the parameters used −

● fd − This is the file descriptor returned by fs.open().

● buffer − This is the buffer that the data will be written to.

● offset − This is the offset in the buffer to start writing at.

● length − This is an integer specifying the number of bytes to read.

● position − This is an integer specifying where to begin reading from

in the file. If position is null, data will be read from the current file

position.

● callback − This is the callback function which gets the three

arguments, (err, bytesRead, buffer).

Example

Page 37 of 93
Let us create a js file named main.js with the following code −

var fs = require("fs");

var buf = new Buffer(1024);

console.log("Going to open an existing file");

fs.open('input.txt', 'r+', function(err, fd) {

if (err) {

return console.error(err);

console.log("File opened successfully!");

console.log("Going to read the file");

fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){

if (err){

console.log(err);

console.log(bytes + " bytes read");

// Print only read bytes to avoid junk.

if(bytes > 0){

console.log(buf.slice(0, bytes).toString());

Page 38 of 93
});

});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to open an existing file

File opened successfully!

Going to read the file

97 bytes read

Ahmedabad Institute Of Technology is giving self learning content

to teach the world in simple and easy way!!!!!

--------------------------------------------------------------------------------------------------------

Closing a File

Syntax

Following is the syntax to close an opened file −

fs.close(fd, callback)

Parameters

Here is the description of the parameters used −

● fd − This is the file descriptor returned by file fs.open() method.

Page 39 of 93
● callback − This is the callback function No arguments other than a

possible exception are given to the completion callback.

Example

Let us create a js file named main.js having the following code −

var fs = require("fs");

var buf = new Buffer(1024);

console.log("Going to open an existing file");

fs.open('input.txt', 'r+', function(err, fd) {

if (err) {

return console.error(err);

console.log("File opened successfully!");

console.log("Going to read the file");

fs.read(fd, buf, 0, buf.length, 0, function(err, bytes) {

if (err) {

console.log(err);

// Print only read bytes to avoid junk.

if(bytes > 0) {

console.log(buf.slice(0, bytes).toString());

Page 40 of 93
}

// Close the opened file.

fs.close(fd, function(err) {

if (err) {

console.log(err);

console.log("File closed successfully.");

});

});

});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to open an existing file

File opened successfully!

Going to read the file

Ahmedabad Institute Of Technology is giving self learning content

to teach the world in simple and easy way!!!!!

File closed successfully.

Page 41 of 93
--------------------------------------------------------------------------------------------------------

Truncate a File

Syntax

Following is the syntax of the method to truncate an opened file −

fs.ftruncate(fd, len, callback)

Parameters

Here is the description of the parameters used −

● fd − This is the file descriptor returned by fs.open().

● len − This is the length of the file after which the file will be

truncated.

● callback − This is the callback function No arguments other than a

possible exception are given to the completion callback.

Example

Let us create a js file named main.js having the following code −

var fs = require("fs");

var buf = new Buffer(1024);

console.log("Going to open an existing file");

fs.open('input.txt', 'r+', function(err, fd) {

if (err) {

return console.error(err);

Page 42 of 93
}

console.log("File opened successfully!");

console.log("Going to truncate the file after 10 bytes");

// Truncate the opened file.

fs.ftruncate(fd, 10, function(err) {

if (err) {

console.log(err);

console.log("File truncated successfully.");

console.log("Going to read the same file");

fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){

if (err) {

console.log(err);

// Print only read bytes to avoid junk.

if(bytes > 0) {

console.log(buf.slice(0, bytes).toString());

Page 43 of 93
// Close the opened file.

fs.close(fd, function(err) {

if (err) {

console.log(err);

console.log("File closed successfully.");

});

});

});

});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to open an existing file

File opened successfully!

Going to truncate the file after 10 bytes

File truncated successfully.

Going to read the same file

Page 44 of 93
Ahmedabad Institute Of Tecnology

File closed successfully.

--------------------------------------------------------------------------------------------------------

Delete a File

Syntax

Following is the syntax of the method to delete a file −

fs.unlink(path, callback)

Parameters

Here is the description of the parameters used −

● path − This is the file name including path.

● callback − This is the callback function No arguments other than a

possible exception are given to the completion callback.

Example

Let us create a js file named main.js having the following code −

var fs = require("fs");

console.log("Going to delete an existing file");

fs.unlink('input.txt', function(err) {

if (err) {

return console.error(err);

console.log("File deleted successfully!");

Page 45 of 93
});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to delete an existing file

File deleted successfully!

--------------------------------------------------------------------------------------------------------

Create a Directory

Syntax

Following is the syntax of the method to create a directory −

fs.mkdir(path[, mode], callback)

Parameters

Here is the description of the parameters used −

● path − This is the directory name including path.

● mode − This is the directory permission to be set. Defaults to 0777.

● callback − This is the callback function No arguments other than a

possible exception are given to the completion callback.

Example

Let us create a js file named main.js having the following code −

var fs = require("fs");

Page 46 of 93
console.log("Going to create directory /tmp/test");

fs.mkdir('/tmp/test',function(err) {

if (err) {

return console.error(err);

console.log("Directory created successfully!");

});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to create directory /tmp/test

Directory created successfully!

--------------------------------------------------------------------------------------------------------

Read a Directory

Syntax

Following is the syntax of the method to read a directory −

fs.readdir(path, callback)

Parameters

Here is the description of the parameters used −

● path − This is the directory name including path.

Page 47 of 93
● callback − This is the callback function which gets two arguments

(err, files) where files is an array of the names of the files in the

directory excluding '.' and '..'.

Example

Let us create a js file named main.js having the following code −

var fs = require("fs");

console.log("Going to read directory /tmp");

fs.readdir("/tmp/",function(err, files) {

if (err) {

return console.error(err);

files.forEach( function (file) {

console.log( file );

});

});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to read directory /tmp

ccmzx99o.out

Page 48 of 93
ccyCSbkF.out

employee.ser

hsperfdata_apache

test

test.txt

--------------------------------------------------------------------------------------------------------

Remove a Directory

Syntax

Following is the syntax of the method to remove a directory −

fs.rmdir(path, callback)

Parameters

Here is the description of the parameters used −

● path − This is the directory name including path.

● callback − This is the callback function No arguments other than a

possible exception are given to the completion callback.

Example

Let us create a js file named main.js having the following code −

var fs = require("fs");

console.log("Going to delete directory /tmp/test");

fs.rmdir("/tmp/test",function(err) {

Page 49 of 93
if (err) {

return console.error(err);

console.log("Going to read directory /tmp");

fs.readdir("/tmp/",function(err, files) {

if (err) {

return console.error(err);

files.forEach( function (file) {

console.log( file );

});

});

});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to read directory /tmp

employee.ser

hsperfdata_apache

Page 50 of 93
EXERCISE:

1.Create Node.js Application to show all File operations.

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________

Page 51 of 93
EXPERIMENT NO: 7 DATE: / /

TITLE: Networking with Node Node JS

OBJECTIVES: On completion of this experiment students will be able to…


➢ know the concept of Socket Programming

THEORY:

Node.js provides the ability to perform socket programming. We can create chat
application or communicate client and server applications using socket programming in
Node.js. The Node.js net module contains functions for creating both servers and clients.

Node.js net module is used to create both servers and clients. This module provides an
asynchronous network wrapper and it can be imported using the following syntax.

var net = require("net")

Methods

Sr.No. Method & Description

1 net.createServer([options][, connectionListener]).Creates a new TCP


server. The connectionListener argument is automatically set as a listener
for the 'connection' event.

2 net.connect(options[, connectionListener]).A factory method, which


returns a new 'net.Socket' and connects to the supplied address and port.

3 net.createConnection(options[, connectionListener]).A factory method,


which returns a new 'net.Socket' and connects to the supplied address and
port.

Page 52 of 93
4 net.connect(port[, host][, connectListener]).Creates a TCP connection to
port on host. If host is omitted, 'localhost' will be assumed. The
connectListener parameter will be added as a listener for the 'connect'
event. It is a factory method which returns a new 'net.Socket'.

5 net.createConnection(port[, host][, connectListener]).Creates a TCP


connection to port on host. If host is omitted, 'localhost' will be assumed.
The connectListener parameter will be added as a listener for the 'connect'
event. It is a factory method which returns a new 'net.Socket'.

6 net.connect(path[, connectListener]).Creates Unix socket connection to


path. The connectListener parameter will be added as a listener for the
'connect' event. It is a factory method which returns a new 'net.Socket'.

7 net.createConnection(path[, connectListener]).Creates Unix socket


connection to path. The connectListener parameter will be added as a
listener for the 'connect' event. It is a factory method which returns a new
'net.Socket'.

8 net.isIP(input).Tests if the input is an IP address. Returns 0 for invalid


strings, 4 for IP version 4 addresses, and 6 for IP version 6 addresses.

9 net.isIPv4(input).Returns true if the input is a version 4 IP address,


otherwise returns false.

Page 53 of 93
10 net.isIPv6(input).Returns true if the input is a version 6 IP address,
otherwise returns false.

Class - net.Server
This class is used to create a TCP or local server.

Methods

Sr.No. Method & Description

1 server.listen(port[, host][, backlog][, callback])

Begin accepting connections on the specified port and host. If the host is
omitted, the server will accept connections directed to any IPv4 address
(INADDR_ANY). A port value of zero will assign a random port.

2 server.listen(path[, callback])

Start a local socket server listening for connections on the given path.

3 server.listen(handle[, callback])

The handle object can be set to either a server or socket (anything with an
underlying _handle member), or a {fd: <n>} object. It will cause the server to
accept connections on the specified handle, but it is presumed that the file
descriptor or handle has already been bound to a port or domain socket.
Listening on a file descriptor is not supported on Windows.

Page 54 of 93
4 server.listen(options[, callback])

The port, host, and backlog properties of options, as well as the optional
callback function, behave as they do on a call to server.listen(port, [host],
[backlog], [callback]) . Alternatively, the path option can be used to specify a
UNIX socket.

5 server.close([callback])

Finally closed when all connections are ended and the server emits a 'close'
event.

6 server.address()

Returns the bound address, the address family name and port of the server as
reported by the operating system.

7 server.unref()

Calling unref on a server will allow the program to exit if this is the only active
server in the event system. If the server is already unrefd, then calling unref
again will have no effect.

Page 55 of 93
8 server.ref()

Opposite of unref, calling ref on a previously unrefd server will not let the
program exit if it's the only server left (the default behavior). If the server is
refd, then calling the ref again will have no effect.

9 server.getConnections(callback)

Asynchronously get the number of concurrent connections on the server.


Works when sockets were sent to forks. Callback should take two arguments
err and count.

Events

Sr.No. Events & Description

1 listening

Emitted when the server has been bound after calling server.listen.

2 connection

Emitted when a new connection is made. Socket object, the connection


object is available to event handler. Socket is an instance of net.Socket.

Page 56 of 93
3 close

Emitted when the server closes. Note that if connections exist, this event is
not emitted until all the connections are ended.

4 error

Emitted when an error occurs. The 'close' event will be called directly
following this event.

Class - net.Socket
This object is an abstraction of a TCP or local socket. net.Socket instances implement a
duplex Stream interface. They can be created by the user and used as a client (with
connect()) or they can be created by Node and passed to the user through the
'connection' event of a server.

Events
net.Socket is an eventEmitter and it emits the following events.

Sr.No. Events & Description

1 lookup

Emitted after resolving the hostname but before connecting. Not applicable
to UNIX sockets.

2 connect

Page 57 of 93
Emitted when a socket connection is successfully established.

3 data

Emitted when data is received. The argument data will be a Buffer or String.
Encoding of data is set by socket.setEncoding().

4 end

Emitted when the other end of the socket sends a FIN packet.

5 timeout

Emitted if the socket times out from inactivity. This is only to notify that the
socket has been idle. The user must manually close the connection.

6 drain

Emitted when the write buffer becomes empty. Can be used to throttle
uploads.

7 error

Emitted when an error occurs. The 'close' event will be called directly

Page 58 of 93
following this event.

8 close

Emitted once the socket is fully closed. The argument had_error is a boolean
which indicates if the socket was closed due to a transmission error.

Properties
net.Socket provides many useful properties to get better control over socket
interactions.

Sr.No. Property & Description

1 socket.bufferSize

This property shows the number of characters currently buffered to be


written.

2 socket.remoteAddress

The string representation of the remote IP address. For example,


'74.125.127.100' or '2001:4860:a005::68'.

Page 59 of 93
3 socket.remoteFamily

The string representation of the remote IP family. 'IPv4' or 'IPv6'.

4 socket.remotePort

The numeric representation of the remote port. For example, 80 or 21.

5 socket.localAddress

The string representation of the local IP address the remote client is


connecting on. For example, if you are listening on '0.0.0.0' and the client
connects on '192.168.1.1', the value would be '192.168.1.1'.

6 socket.localPort

The numeric representation of the local port. For example, 80 or 21.

7 socket.bytesRead

The amount of received bytes.

8 socket.bytesWritten

Page 60 of 93
The amount of bytes sent.

Methods

Sr.No. Method & Description

1 new net.Socket([options])

Construct a new socket object.

2 socket.connect(port[, host][, connectListener])

Opens the connection for a given socket. If port and host are given, then the
socket will be opened as a TCP socket, if host is omitted, localhost will be
assumed. If a path is given, the socket will be opened as a Unix socket to
that path.

3 socket.connect(path[, connectListener])

Opens the connection for a given socket. If port and host are given, then the
socket will be opened as a TCP socket, if host is omitted, localhost will be
assumed. If a path is given, the socket will be opened as a Unix socket to
that path.

4 socket.setEncoding([encoding])

Page 61 of 93
Set the encoding for the socket as a Readable Stream.

5 socket.write(data[, encoding][, callback])

Sends data on the socket. The second parameter specifies the encoding in
the case of a string--it defaults to UTF8 encoding.

6 socket.end([data][, encoding])

Half-closes the socket, i.e., it sends a FIN packet. It is possible the server will
still send some data.

7 socket.destroy()

Ensures that no more I/O activity happens on this socket. Necessary only in
case of errors (parse error or so).

8 socket.pause()

Pauses the reading of data. That is, 'data' events will not be emitted. Useful
to throttle back an upload.

9 socket.resume()

Page 62 of 93
Resumes reading after a call to pause().

10 socket.setTimeout(timeout[, callback])

Sets the socket to timeout after timeout milliseconds of inactivity on the


socket. By default, net.Socket does not have a timeout.

11 socket.setNoDelay([noDelay])

Disables the Nagle algorithm. By default, TCP connections use the Nagle
algorithm, they buffer data before sending it off. Setting true for noDelay
will immediately fire off data each time socket.write() is called. noDelay
defaults to true.

12 socket.setKeepAlive([enable][, initialDelay])

Enable/disable keep-alive functionality, and optionally set the initial delay


before the first keepalive probe is sent on an idle socket. enable defaults to
false.

13 socket.address()

Returns the bound address, the address family name, and the port of the
socket as reported by the operating system. Returns an object with three
properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }.

Page 63 of 93
14 socket.unref()

Calling unref on a socket will allow the program to exit if this is the only
active socket in the event system. If the socket is already unrefd, then
calling unref again will have no effect.

15 socket.ref()

Opposite of unref, calling ref on a previously unrefd socket will not let the
program exit if it's the only socket left (the default behavior). If the socket is
refd, then calling ref again will have no effect.

Node.js Net Example

In this example, we are using two command prompts:

● Node.js command prompt for server.

● Window's default command prompt for client.

Server:

File: net_server1.js

var net = require('net');

var server = net.createServer(function(connection) {

console.log('client connected');

connection.on('end', function() {

Page 64 of 93
console.log('client disconnected');

});

connection.write('Hello World!\r\n');

connection.pipe(connection);

});

server.listen(8080, function() {

console.log('server is listening');

});

Open Node.js command prompt and run the following code:

node net_server.js

client:

File: net_client1.js

var net = require('net');

var client = net.connect({port: 8080}, function() {

console.log('connected to server!');

});

client.on('data', function(data) {

console.log(data.toString());

client.end();

});

client.on('end', function() {

Page 65 of 93
console.log('disconnected from server');

});

Open Node.js command prompt and run the following code:

node net_client.js

Verify the Output.

connected to server!

Hello World!

disconnected from server

Verify the Output on the terminal where server.js is running.

server is listening

client connected

client disconnected

EXERCISE:

1.Create Node.js Application to show client server communication.

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________

Page 66 of 93
EXPERIMENT NO: 8 DATE: / /

TITLE: Node JS Web Module

OBJECTIVES: On completion of this experiment students will be able to…


➢ know the concept of the web module and architecture of it.

THEORY:

What is a Web Server?


A Web Server is a software application which handles HTTP requests sent by the HTTP
client, like web browsers, and returns web pages in response to the clients. Web
servers usually deliver html documents along with images, style sheets, and scripts.
Most of the web servers support server-side scripts, using scripting languages or
redirecting the task to an application server which retrieves data from a database and
performs complex logic and then sends a result to the HTTP client through the Web
server.
Apache web server is one of the most commonly used web servers. It is an open source
project.

Web Application Architecture

A Web application is usually divided into four layers −

Page 67 of 93
● Client − This layer consists of web browsers, mobile browsers or

applications which can make HTTP requests to the web server.

● Server − This layer has the Web server which can intercept the

requests made by the clients and pass them the response.

● Business − This layer contains the application server which is

utilized by the web server to do the required processing. This layer

interacts with the data layer via the database or some external

programs.

● Data − This layer contains the databases or any other source of

data.

Creating a Web Server using Node


Node.js provides an http module which can be used to create an HTTP client of a server.
Following is the bare minimum structure of the HTTP server which listens at 8081 port.

Create a js file named server.js −

File: server.js

var http = require('http');

var fs = require('fs');

var url = require('url');

// Create a server

http.createServer( function (request, response) {

// Parse the request containing file name

var pathname = url.parse(request.url).pathname;

Page 68 of 93
// Print the name of the file for which request is made.

console.log("Request for " + pathname + " received.");

// Read the requested file content from file system

fs.readFile(pathname.substr(1), function (err, data) {

if (err) {

console.log(err)

// HTTP Status: 404 : NOT FOUND

// Content Type: text/plain

response.writeHead(404, {'Content-Type': 'text/html'});

} else {

//Page found

// HTTP Status: 200 : OK

// Content Type: text/plain

response.writeHead(200, {'Content-Type': 'text/html'});

// Write the content of the file to response body

response.write(data.toString());

// Send the response body

response.end();

Page 69 of 93
});

}).listen(8081);

// Console will print the message

console.log('Server running at http://127.0.0.1:8081/');

Next let's create the following html file named index.htm in the same directory where
you created server.js.
File: index.htm

<html>

<head>

<title>Sample Page</title>

</head>

<body>

Hello World!

</body>

</html>

Now let us run the server.js to see the result −

$ node server.js

Verify the Output.

Server running at http://127.0.0.1:8081/

Page 70 of 93
Make a request to Node.js server

Open http://127.0.0.1:8081/index.html in any browser to see the following


result.

Creating Web client using Node


A web client can be created using http module. Let's check the following example.

Create a js file named client.js −

File: client.js

var http = require('http');

// Options to be used by request

var options = {

host: 'localhost',

port: '8081',

path: '/index.html'

};

// Callback function is used to deal with response

var callback = function(response) {

// Continuously update stream with data

var body = '';

response.on('data', function(data) {

body += data;

Page 71 of 93
});

response.on('end', function() {

// Data received completely.

console.log(body);

});

// Make a request to the server

var req = http.request(options, callback);

req.end();

Now run the client.js from a different command terminal other than

server.js to see the result −

$ node client.js

Verify the Output.

<html>

<head>

<title>Sample Page</title>

</head>

<body>

Hello World!

Page 72 of 93
</body>

</html>

Verify the Output at server end.

Server running at http://127.0.0.1:8081/

Request for /index.htm received.

EXERCISE:

1.Create Node.js Application to run on web client as well as server.

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________

Page 73 of 93
EXPERIMENT NO: 9 DATE: / /

TITLE: MongoDB with NodeJs

OBJECTIVES: On completion of this experiment students will be able to…


➢ know the concept of Connectivity of MongoDB with Nodejs

THEORY:

Install MongoDB :

You can download a free MongoDB database at https://www.mongodb.com.

Or get started right away with a MongoDB cloud service at


https://www.mongodb.com/cloud/atlas.

Let us try to access a MongoDB database with Node.js.

To download and install the official MongoDB driver, open the Command Terminal and
execute the following:

Download and install mongodb package:


C:\Users\Your Name>npm install mongodb

Note: First open another terminal an run command mongod to start your mongoDB

Node.js MongoDB Create Database

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

console.log("Database created!");

db.close();

Page 74 of 93
});

C:\Users>node demo_create_mongo_db.js

Node.js MongoDB Create Collection:

A collection in MongoDB is the same as a table in MySQL

Creating a Collection

To create a collection in MongoDB, use the createCollection() method:

Example
Create a collection called "customers":

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

dbo.createCollection("customers", function(err, res) {

if (err) throw err;

console.log("Collection created!");

db.close();

});

});

Page 75 of 93
EXERCISE:

1.Create Node.js Application to Connect Node JS with MongoDB

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________

Page 76 of 93
EXPERIMENT NO: 10 DATE: / /

TITLE: Operations on data in MongoDB

OBJECTIVES: On completion of this experiment students will be able to…


➢ MongoDB and operations like (Insert, Find, Query, Sort, Delete,
Update)

THEORY:

To insert a record, or document as it is called in MongoDB, into a collection, we use the


insertOne() method.

A document in MongoDB is the same as a record in MySQL

The first parameter of the insertOne() method is an object containing the name(s) and
value(s) of each field in the document you want to insert.

It also takes a callback function where you can work with any errors, or the result of the
insertion:

Example
Insert a document in the "customers" collection:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

var myobj = { name: "Company Inc", address: "Highway 37" };

dbo.collection("customers").insertOne(myobj, function(err, res) {

Page 77 of 93
if (err) throw err;

console.log("1 document inserted");

db.close();

});

});

Insert Multiple Documents

To insert multiple documents into a collection in MongoDB, we use the insertMany()


method.

The first parameter of the insertMany() method is an array of objects, containing the
data you want to insert.

It also takes a callback function where you can work with any errors, or the result of the
insertion:

Example
Insert multiple documents in the "customers" collection:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

var myobj = [

{ name: 'John', address: 'Highway 71'},

Page 78 of 93
{ name: 'Peter', address: 'Lowstreet 4'},

{ name: 'Amy', address: 'Apple st 652'},

{ name: 'Hannah', address: 'Mountain 21'},

{ name: 'Michael', address: 'Valley 345'},

{ name: 'Sandy', address: 'Ocean blvd 2'},

{ name: 'Betty', address: 'Green Grass 1'},

{ name: 'Richard', address: 'Sky st 331'},

{ name: 'Susan', address: 'One way 98'},

{ name: 'Vicky', address: 'Yellow Garden 2'},

{ name: 'Ben', address: 'Park Lane 38'},

{ name: 'William', address: 'Central st 954'},

{ name: 'Chuck', address: 'Main Road 989'},

{ name: 'Viola', address: 'Sideway 1633'}

];

dbo.collection("customers").insertMany(myobj, function(err, res) {

if (err) throw err;

console.log("Number of documents inserted: " + res.insertedCount);

db.close();

});

Page 79 of 93
});

The _id Field

If you do not specify an _id field, then MongoDB will add one for you and assign a
unique id for each document.

In the example above no _id field was specified, and as you can see from the result
object, MongoDB assigned a unique _id for each document.

If you do specify the _id field, the value must be unique for each document:

Example
Insert three records in a "products" table, with specified _id fields:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

var myobj = [

{ _id: 154, name: 'Chocolate Heaven'},

{ _id: 155, name: 'Tasty Lemon'},

{ _id: 156, name: 'Vanilla Dream'}

];

dbo.collection("products").insertMany(myobj, function(err, res) {

if (err) throw err;

Page 80 of 93
console.log(res);

db.close();

});

});

Node.js MongoDB Find


In MongoDB we use the find and findOne methods to find data in a collection.
Just like the SELECT statement is used to find data in a table in a MySQL database.
Find One

To select data from a collection in MongoDB, we can use the findOne() method.

The findOne() method returns the first occurrence in the selection.

The first parameter of the findOne() method is a query object. In this example we use an
empty query object, which selects all documents in a collection (but returns only the
first document).

Example
Find the first document in the customers collection:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

dbo.collection("customers").findOne({}, function(err, result) {

if (err) throw err;

console.log(result.name);

Page 81 of 93
db.close();

});

});

Find All

To select data from a table in MongoDB, we can also use the find() method.

The find() method returns all occurrences in the selection.

The first parameter of the find() method is a query object. In this example we use an
empty query object, which selects all documents in the collection.

No parameters in the find() method gives you the same result as SELECT * in MySQL.

Example
Find all documents in the customers collection:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

dbo.collection("customers").find({}).toArray(function(err, result) {

if (err) throw err;

console.log(result);

db.close();

});

Page 82 of 93
});

Find Some

The second parameter of the find() method is the projection object that describes which
fields to include in the result.

This parameter is optional, and if omitted, all fields will be included in the result.

Example
Return the fields "name" and "address" of all documents in the customers collection:
var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

dbo.collection("customers").find({}, { projection: { _id: 0, name: 1, address:


1 } }).toArray(function(err, result) {

if (err) throw err;

console.log(result);

db.close();

});

});

Node.js MongoDB Query


Filter the Result

When finding documents in a collection, you can filter the result by using a query object.

Page 83 of 93
The first argument of the find() method is a query object, and is used to limit the search.

Example
Find documents with the address "Park Lane 38":
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

var query = { address: "Park Lane 38" };

dbo.collection("customers").find(query).toArray(function(err, result) {

if (err) throw err;

console.log(result);

db.close();

});

});

Filter With Regular Expressions

You can write regular expressions to find exactly what you are searching for.

Regular expressions can only be used to query strings.

To find only the documents where the "address" field starts with the letter "S", use the
regular expression /^S/:

Example
Find documents where the address starts with the letter "S":
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

Page 84 of 93
MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

var query = { address: /^S/ };

dbo.collection("customers").find(query).toArray(function(err, result) {

if (err) throw err;

console.log(result);

db.close();

});

});

Node.js MongoDB Sort


Sort the Result

Use the sort() method to sort the result in ascending or descending order.

The sort() method takes one parameter, an object defining the sorting order.

Example
Sort the result alphabetically by name:
var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

Page 85 of 93
var mysort = { name: 1 };

dbo.collection("customers").find().sort(mysort).toArray(function(err, result) {

if (err) throw err;

console.log(result);

db.close();

});

});

Sort Descending
Example

Sort the result reverse alphabetically by name:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

var mysort = { name: -1 };

dbo.collection("customers").find().sort(mysort).toArray(function(err, result) {

if (err) throw err;

console.log(result);

db.close();

Page 86 of 93
});

});

Node.js MongoDB Delete


Delete Document

To delete a record, or document as it is called in MongoDB, we use the deleteOne()


method.

The first parameter of the deleteOne() method is a query object defining which
document to delete.

Note: If the query finds more than one document, only the first occurrence is deleted.

Example
Delete the document with the address "Mountain 21":
var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

var myquery = { address: 'Mountain 21' };

dbo.collection("customers").deleteOne(myquery, function(err, obj) {

if (err) throw err;

console.log("1 document deleted");

db.close();

});

Page 87 of 93
});

Delete Many

To delete more than one document, use the deleteMany() method.

The first parameter of the deleteMany() method is a query object defining which
documents to delete.

Example
Delete all documents were the address starts with the letter "O":
var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

var myquery = { address: /^O/ };

dbo.collection("customers").deleteMany(myquery, function(err, obj) {

if (err) throw err;

console.log(obj.result.n + " document(s) deleted");

db.close();

});

});

Node.js MongoDB Drop


Drop Collection

Page 88 of 93
You can delete a table, or collection as it is called in MongoDB, by using the drop()
method.

The drop() method takes a callback function containing the error object and the result
parameter which returns true if the collection was dropped successfully, otherwise it
returns false.

Example
Delete the "customers" table:

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

dbo.collection("customers").drop(function(err, delOK) {

if (err) throw err;

if (delOK) console.log("Collection deleted");

db.close();

});

});

db.dropCollection

You can also use the dropCollection() method to delete a table (collection).

The dropCollection() method takes two parameters: the name of the collection and a
callback function.

Page 89 of 93
Example
Delete the "customers" collection, using dropCollection():
var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

dbo.dropCollection("customers", function(err, delOK) {

if (err) throw err;

if (delOK) console.log("Collection deleted");

db.close();

});

});

Node.js MongoDB Update


Update Document

You can update a record, or document as it is called in MongoDB, by using the


updateOne() method.

The first parameter of the updateOne() method is a query object defining which
document to update.

Note: If the query finds more than one record, only the first occurrence is updated.

The second parameter is an object defining the new values of the document.

Page 90 of 93
Example

Update the document with the address "Valley 345" to name="Mickey" and
address="Canyon 123":

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

var myquery = { address: "Valley 345" };

var newvalues = { $set: {name: "Mickey", address: "Canyon 123" } };

dbo.collection("customers").updateOne(myquery, newvalues, function(err, res) {

if (err) throw err;

console.log("1 document updated");

db.close();

});

});

Update Only Specific Fields

When using the $set operator, only the specified fields are updated:

Example
Update the address from "Valley 345" to "Canyon 123":

var MongoClient = require('mongodb').MongoClient;

Page 91 of 93
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

var myquery = { address: "Valley 345" };

var newvalues = {$set: {address: "Canyon 123"} };

dbo.collection("customers").updateOne(myquery, newvalues, function(err, res) {

if (err) throw err;

console.log("1 document updated");

db.close();

});

});

Update Many Documents

To update all documents that meets the criteria of the query, use the updateMany()
method.

Example
Update all documents where the name starts with the letter "S":

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://127.0.0.1:27017/";

Page 92 of 93
MongoClient.connect(url, function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

var myquery = { address: /^S/ };

var newvalues = {$set: {name: "Minnie"} };

dbo.collection("customers").updateMany(myquery, newvalues, function(err, res) {

if (err) throw err;

console.log(res.result.nModified + " document(s) updated");

db.close();

});

});

EXERCISE:

1.Create Node.js Application to show all MongoDB operations.

EVALUATION:

Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)

Signature with date: ________________

Page 93 of 93

You might also like