5.AWP Labmanual New
5.AWP Labmanual New
5.AWP Labmanual New
Laboratory Manual
Year: 2022-2023
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
1. Introduction to
HTML,CSS,JavaScript, BootStap
2.ExExpressions in AngularJS
Page 2 of 93
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 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.
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 4 of 93
</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">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.c
ss">
</head>
<body>
<h1>Hello, world!</h1>
<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.
Page 6 of 93
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
Page 7 of 93
EXPERIMENT NO: 2 DATE: / /
THEORY:
What is AngularJS
AngularJS extends HTML attributes with Directives, and binds data to HTML with
Expressions.
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>
The ng-model directive binds the value of HTML controls (input, select, textarea) to
application data.
<!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 ng-bind="name"></p>
</div>
</body>
</html>
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 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="">
</div>
</body>
</html>
EXERCISE:
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
Page 10 of 93
EXPERIMENT NO: 3 DATE: / /
THEORY:
Forms in AngularJS provide data-binding and validation of input controls.
Input Controls
● 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>
Page 11 of 93
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.firstname = "John";
});
</script>
</body>
</html>
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="">
<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>
</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">
<form name="myForm">
<input name="myInput" ng-model="myInput" required my-directive>
</form>
<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:
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
Page 14 of 93
EXPERIMENT NO: 4 DATE: / /
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.
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:
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
Page 19 of 93
EXPERIMENT NO: 5 DATE: / /
THEORY:
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 20 of 93
What is a Node.js File?
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 21 of 93
crypto To handle OpenSSL cryptographic functions
Page 22 of 93
punycode Deprecated. A character encoding scheme
Page 23 of 93
vm To compile JavaScript code in a virtual machine
include Modules
To include a module, use the require() function with the name of the module:
Now your application has access to the HTTP module, and is able to create a server:
res.end('Hello World!');
}).listen(8080);
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"
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:
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 /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
Page 25 of 93
EXPERIMENT NO: 6 DATE: / /
THEORY:
POSIX functions. The Node File System (fs) module can be imported
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
------------------------------------------------------------------------------------------------------
var fs = require("fs");
Page 26 of 93
// Asynchronous read
if (err) {
return console.error(err);
});
// Synchronous read
console.log("Program Ended");
$ node main.js
Program Ended
Page 27 of 93
● Open a File
Syntax
mode −
Parameters
● mode − It sets the file mode (permission and sticky bits), but only if
(err, fd).
Flags
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 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 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
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");
if (err) {
return console.error(err);
});
Page 30 of 93
$ node main.js
--------------------------------------------------------------------------------------------------------
Syntax
Following is the syntax of the method to get the information about a file
fs.stat(path, callback)
Parameters
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
stats.isDirectory()
2
stats.isBlockDevice()
3
stats.isCharacterDevice()
4
stats.isSymbolicLink()
5
stats.isFIFO()
6
Page 32 of 93
Returns true if file type of a FIFO.
stats.isSocket()
7
Example
var fs = require("fs");
if (err) {
return console.error(err);
console.log(stats);
});
Page 33 of 93
Now run the main.js to see the result −
$ node main.js
dev: 1792,
mode: 33188,
nlink: 1,
uid: 48,
gid: 48,
rdev: 0,
blksize: 4096,
ino: 4318127,
size: 97,
blocks: 8,
Page 34 of 93
Got file info successfully!
isFile ? true
isDirectory ? false
--------------------------------------------------------------------------------------------------------
Writing a File
Syntax
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
● path − This is the string having the file name including path.
Example
Page 35 of 93
var fs = require("fs");
if (err) {
return console.error(err);
if (err) {
return console.error(err);
});
});
$ node main.js
Page 36 of 93
Data written successfully!
--------------------------------------------------------------------------------------------------------
Reading a File
Syntax
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
● buffer − This is the buffer that the data will be written to.
in the file. If position is null, data will be read from the current file
position.
Example
Page 37 of 93
Let us create a js file named main.js with the following code −
var fs = require("fs");
if (err) {
return console.error(err);
if (err){
console.log(err);
console.log(buf.slice(0, bytes).toString());
Page 38 of 93
});
});
$ node main.js
97 bytes read
--------------------------------------------------------------------------------------------------------
Closing a File
Syntax
fs.close(fd, callback)
Parameters
Page 39 of 93
● callback − This is the callback function No arguments other than a
Example
var fs = require("fs");
if (err) {
return console.error(err);
if (err) {
console.log(err);
if(bytes > 0) {
console.log(buf.slice(0, bytes).toString());
Page 40 of 93
}
fs.close(fd, function(err) {
if (err) {
console.log(err);
});
});
});
$ node main.js
Page 41 of 93
--------------------------------------------------------------------------------------------------------
Truncate a File
Syntax
Parameters
● len − This is the length of the file after which the file will be
truncated.
Example
var fs = require("fs");
if (err) {
return console.error(err);
Page 42 of 93
}
if (err) {
console.log(err);
if (err) {
console.log(err);
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);
});
});
});
});
$ node main.js
Page 44 of 93
Ahmedabad Institute Of Tecnology
--------------------------------------------------------------------------------------------------------
Delete a File
Syntax
fs.unlink(path, callback)
Parameters
Example
var fs = require("fs");
fs.unlink('input.txt', function(err) {
if (err) {
return console.error(err);
Page 45 of 93
});
$ node main.js
--------------------------------------------------------------------------------------------------------
Create a Directory
Syntax
Parameters
Example
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);
});
$ node main.js
--------------------------------------------------------------------------------------------------------
Read a Directory
Syntax
fs.readdir(path, callback)
Parameters
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
Example
var fs = require("fs");
fs.readdir("/tmp/",function(err, files) {
if (err) {
return console.error(err);
console.log( file );
});
});
$ node main.js
ccmzx99o.out
Page 48 of 93
ccyCSbkF.out
employee.ser
hsperfdata_apache
test
test.txt
--------------------------------------------------------------------------------------------------------
Remove a Directory
Syntax
fs.rmdir(path, callback)
Parameters
Example
var fs = require("fs");
fs.rmdir("/tmp/test",function(err) {
Page 49 of 93
if (err) {
return console.error(err);
fs.readdir("/tmp/",function(err, files) {
if (err) {
return console.error(err);
console.log( file );
});
});
});
$ node main.js
employee.ser
hsperfdata_apache
Page 50 of 93
EXERCISE:
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
Page 51 of 93
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 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'.
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
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)
Events
1 listening
Emitted when the server has been bound after calling server.listen.
2 connection
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.
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.
1 socket.bufferSize
2 socket.remoteAddress
Page 59 of 93
3 socket.remoteFamily
4 socket.remotePort
5 socket.localAddress
6 socket.localPort
7 socket.bytesRead
8 socket.bytesWritten
Page 60 of 93
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 61 of 93
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 62 of 93
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 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.
Server:
File: net_server1.js
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');
});
node net_server.js
client:
File: net_client1.js
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');
});
node net_client.js
connected to server!
Hello World!
server is listening
client connected
client disconnected
EXERCISE:
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
Page 66 of 93
EXPERIMENT NO: 8 DATE: / /
THEORY:
Page 67 of 93
● Client − This layer consists of web browsers, mobile browsers or
● Server − This layer has the Web server which can intercept the
interacts with the data layer via the database or some external
programs.
data.
File: server.js
var fs = require('fs');
// Create a server
Page 68 of 93
// Print the name of the file for which request is made.
if (err) {
console.log(err)
} else {
//Page found
response.write(data.toString());
response.end();
Page 69 of 93
});
}).listen(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>
$ node server.js
Page 70 of 93
Make a request to Node.js server
File: client.js
var options = {
host: 'localhost',
port: '8081',
path: '/index.html'
};
response.on('data', function(data) {
body += data;
Page 71 of 93
});
response.on('end', function() {
console.log(body);
});
req.end();
Now run the client.js from a different command terminal other than
$ node client.js
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
Page 72 of 93
</body>
</html>
EXERCISE:
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
Page 73 of 93
EXPERIMENT NO: 9 DATE: / /
THEORY:
Install MongoDB :
To download and install the official MongoDB driver, open the Command Terminal and
execute the following:
Note: First open another terminal an run command mongod to start your mongoDB
console.log("Database created!");
db.close();
Page 74 of 93
});
C:\Users>node demo_create_mongo_db.js
Creating a Collection
Example
Create a collection called "customers":
console.log("Collection created!");
db.close();
});
});
Page 75 of 93
EXERCISE:
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
Page 76 of 93
EXPERIMENT NO: 10 DATE: / /
THEORY:
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:
Page 77 of 93
if (err) throw err;
db.close();
});
});
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 myobj = [
Page 78 of 93
{ name: 'Peter', address: 'Lowstreet 4'},
];
db.close();
});
Page 79 of 93
});
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 myobj = [
];
Page 80 of 93
console.log(res);
db.close();
});
});
To select data from a collection in MongoDB, we can use the findOne() method.
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:
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 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:
dbo.collection("customers").find({}).toArray(function(err, result) {
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;
console.log(result);
db.close();
});
});
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/";
dbo.collection("customers").find(query).toArray(function(err, result) {
console.log(result);
db.close();
});
});
You can write regular expressions to find exactly what you are searching for.
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) {
dbo.collection("customers").find(query).toArray(function(err, result) {
console.log(result);
db.close();
});
});
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;
Page 85 of 93
var mysort = { name: 1 };
dbo.collection("customers").find().sort(mysort).toArray(function(err, result) {
console.log(result);
db.close();
});
});
Sort Descending
Example
dbo.collection("customers").find().sort(mysort).toArray(function(err, result) {
console.log(result);
db.close();
Page 86 of 93
});
});
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;
db.close();
});
Page 87 of 93
});
Delete Many
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;
db.close();
});
});
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:
dbo.collection("customers").drop(function(err, delOK) {
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;
db.close();
});
});
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":
db.close();
});
});
When using the $set operator, only the specified fields are updated:
Example
Update the address from "Valley 345" to "Canyon 123":
Page 91 of 93
var url = "mongodb://localhost:27017/";
db.close();
});
});
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":
Page 92 of 93
MongoClient.connect(url, function(err, db) {
db.close();
});
});
EXERCISE:
EVALUATION:
Understanding /
Involvement Timely
Problem solving Total
Completion
(10)
(4) (3)
(3)
Page 93 of 93