AWP manual
AWP manual
AWP manual
Laboratory Manual
Year: 2024-2025
NAME
ENROLLMENT NO
BATCH
YEAR
CERTIFICATE
Date of Submission:-__________________________
Page 2 of 67
DEPARTMENT OF INFORMATION TECHNOLOGY
VISION
“To impart quality education and research in Information Technology to produce a
competent, committed and goal oriented workforce to fulfill the needs of the local and
global IT Industry.”
Page 3 of 67
INDEX
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 4 of 67
EXPERIMENT NO: 1 DATE: / /
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.
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 5 of 67
● 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.
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">
</head>
<body>
<h1>Hello, world!</h1>
Page 6 of 67
</body>
</html>
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>
<script
src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/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.
Page 7 of 67
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.
EVALUATION:
Understanding / Timely
Involvement (4) Total (10)
Problem solving (3) Completion (3)
Page 8 of 67
EXPERIMENT NO: 2 DATE: / /
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.
Page 9 of 67
AngularJS Expressions
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.
<!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 / Timely
Involvement (4) Total (10)
Problem solving (3) Completion (3)
Page 10 of 67
EXPERIMENT NO: 3 DATE: / /
● input elements
● select elements
● button elements
● textarea elements
Data-Binding
The ng-model directive binds the input controller to the rest of your application.
<!DOCTYPE html>
<html lang="en">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<script>
Page 11 of 67
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.firstname = "John";
});
</script>
</body>
</html>
<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>
</body>
</html>
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>
Page 12 of 67
<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>
EXERCISE:
1.Create student information form and apply validation
EVALUATION:
Understanding / Timely
Involvement (4) Total (10)
Problem solving (3) Completion (3)
Page 13 of 67
EXPERIMENT NO: 4 DATE: / /
Page 14 of 67
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
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=
Page 15 of 67
"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">
<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
Page 16 of 67
.when('/', {
templateUrl : 'first.html',
controller : 'FirstController'
})
.when('/second', {
templateUrl : 'second.html',
controller : 'SecondController'
})
.when('/third', {
templateUrl : 'third.html',
controller : 'ThirdController'
})
.otherwise({redirectTo: '/'});
});
<!-- 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 / Timely
Involvement (4) Total (10)
Problem solving (3) Completion (3)
Page 17 of 67
EXPERIMENT NO: 5 DATE: / /
A common task for a web server can be to open a file on the server and return the content to
the client.
Node.js eliminates the waiting, and simply continues with the next request.
Page 18 of 67
● 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?
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.
Module Description
Page 19 of 67
domain Deprecated. To handle unhandled errors
Page 20 of 67
util To access utility functions
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.
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
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:
Page 21 of 67
Initiate 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:
EVALUATION:
Understanding / Timely
Involvement (4) Total (10)
Problem solving (3) Completion (3)
Page 22 of 67
EXPERIMENT NO: 6 DATE: / /
THEORY:
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");
// 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");
Page 23 of 67
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!!!!!
● 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 −
Flags
Flags for read/write operations are −
r :Open file for reading. An exception occurs if the file does not exist.
1
Page 24 of 67
r+:Open file for reading and writing. An exception occurs if the file does not
2
exist.
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).
w+:Open file for reading and writing. The file is created (if it does not exist) or
7
truncated (if it exists).
a:Open file for appending. The file is created if it does not exist.
9
Page 25 of 67
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
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 −
$ 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)
Page 26 of 67
Parameters
Here is the description of the parameters used −
stats.isFile()
1
stats.isDirectory()
2
stats.isBlockDevice()
3
Page 27 of 67
stats.isCharacterDevice()
4
stats.isSymbolicLink()
5
stats.isFIFO()
6
stats.isSocket()
7
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 28 of 67
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)
}
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'
Page 29 of 67
● 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 −
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
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.
Page 30 of 67
Parameters
Here is the description of the parameters used −
Example
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());
}
});
});
Now run the main.js to see the result −
$ node main.js
Verify the Output.
Page 31 of 67
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.
● 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 32 of 67
// 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.
--------------------------------------------------------------------------------------------------------
Truncate a File
Syntax
Following is the syntax of the method to truncate an opened file −
Parameters
Here is the description of the parameters used −
Page 33 of 67
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 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");
Page 34 of 67
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
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!");
});
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)
Page 35 of 67
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 36 of 67
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
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) {
if (err) {
return console.error(err);
}
console.log("Going to read directory /tmp");
Page 37 of 67
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
EXERCISE:
EVALUATION:
Understanding / Timely
Involvement (4) Total (10)
Problem solving (3) Completion (3)
Page 38 of 67
EXPERIMENT NO: 7 DATE: / /
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.
Methods
Page 39 of 67
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'.
Page 40 of 67
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
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 41 of 67
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 42 of 67
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)
Events
1 listening
Emitted when the server has been bound after calling server.listen.
2 connection
Page 43 of 67
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.
1 lookup
Emitted after resolving the hostname but before connecting. Not applicable
to UNIX sockets.
2 connect
Page 44 of 67
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
Page 45 of 67
Emitted when an error occurs. The 'close' event will be called directly
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.
1 socket.bufferSize
2 socket.remoteAddress
Page 46 of 67
3 socket.remoteFamily
4 socket.remotePort
5 socket.localAddress
6 socket.localPort
7 socket.bytesRead
8 socket.bytesWritten
Page 47 of 67
The amount of bytes sent.
Methods
1 new net.Socket([options])
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 48 of 67
Set the encoding for the socket as a Readable Stream.
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 49 of 67
Resumes reading after a call to pause().
10 socket.setTimeout(timeout[, callback])
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])
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 50 of 67
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.
Server:
File: net_server1.js
var net = require('net');
console.log('client connected');
connection.on('end', function() {
console.log('client disconnected');
});
connection.write('Hello World!\r\n');
connection.pipe(connection);
});
server.listen(8080, function() {
console.log('server is listening');
});
Page 51 of 67
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() {
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 / Timely
Involvement (4) Total (10)
Problem solving (3) Completion (3)
Page 52 of 67
EXPERIMENT NO: 8 DATE: / /
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 53 of 67
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 54 of 67
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/
Make a request to Node.js server
Page 55 of 67
// 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!
</body>
</html>
Verify the Output at server end.
Server running at http://127.0.0.1:8081/
Request for /index.htm received.
EXERCISE:
EVALUATION:
Understanding / Timely
Involvement (4) Total (10)
Problem solving (3) Completion (3)
Page 56 of 67
EXPERIMENT NO: 9 DATE: / /
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();
});
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;
Page 57 of 67
console.log("Collection created!");
db.close();
});
});
EXERCISE:
EVALUATION:
Understanding / Timely
Involvement (4) Total (10)
Problem solving (3) Completion (3)
Page 58 of 67
EXPERIMENT NO: 10 DATE: / /
Page 59 of 67
if (err) throw err;
var dbo = db.db("mydb");
var myobj = [
{ name: 'John', address: 'Highway 71'},
{ 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();
});
});
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'}
Page 60 of 67
];
dbo.collection("products").insertMany(myobj, function(err, res) {
if (err) throw err;
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);
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;
Page 61 of 67
var dbo = db.db("mydb");
dbo.collection("customers").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
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.
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();
Page 62 of 67
});
});
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/";
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");
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
Page 63 of 67
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();
});
});
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();
});
});
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":
Page 64 of 67
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
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.
Example
Delete the "customers" collection, using dropCollection():
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
Page 65 of 67
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.
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;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
Page 66 of 67
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();
});
});
EXERCISE:
EVALUATION:
Understanding / Timely
Involvement (4) Total (10)
Problem solving (3) Completion (3)
Page 67 of 67