WT - Unit 5
WT - Unit 5
Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Unit 5
Web Application Development Framework: Fundamentals of Angular JS and NODE JS
Angular Java Script- Introduction to Angular JS Expressions: ARRAY, Objects, Strings, Angular
JS Form Validation & Form Submission. Node.js- Introduction, Advantages, Node.js Process
Model, Node JS Modules, Node JS File system, Node JS URL module, Node JS Events.
Example
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body>
<div ng-app="">
<p>Input something in the input box:</p>
<p>Name : <input type="text"
ng-model="name"
placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>
</div>
</body>
</html>
Page 1
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
ng new my-app
Step-4: Run the application using the following command in the terminal
ng serve
Angular JS Expressions
Data binding is a very useful and powerful feature used in software development
technologies. It acts as a bridge between the view and business logic of the application.
AngularJS follows Two-Way data binding model
The one-way data binding is an approach where a value is taken from the data model and
inserted into an HTML element. There is no way to update model from view. It is used in
classical template systems. These systems bind data in only one direction.
Data-binding in Angular apps is the automatic synchronization of data between the model and
view components.
In AngularJS, expressions are used to bind application data to HTML. AngularJS resolves the
expression, and return the result exactly where the expression is written.
The expressions in AngularJS are written in double braces: {{ expression }}. They behave
similar to ng-bind directives: ng-bind=”expression”.
Example
<!DOCTYPE html>
Page 2
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<title>AngularJS Expression</title>
</head>
<body>
<h1 style="color:green">
KHIT
</h1>
<h3>AngularJS Expressions</h3>
<div ng-app=""
ng-init="sort={one:'quick sort',
two:'merge sort',
three:'bubble sort'}">
Angular JS Objects
Syntax: <p>Roll No: {{student.rollno}}</p>
Angular JS Strings
Syntax: <p>Hello {{student.firstname + " " + student.lastname}}!</p>
Angular JS ARRAY
Syntax: <p>Marks(Math): {{marks[3]}}</p>
Example
<html>
<head>
<title>AngularJS Expressions</title>
</head>
<body>
<h1>Sample Application</h1>
<div ng-app = "" ng-init = "quantity = 1;cost = 30;
student = {firstname:'Vamshi',lastname:'Krishna',rollno:101};
marks = [80,90,75,73,60]">
<p>Hello {{student.firstname + " " + student.lastname}}!</p>
<p>Expense on Books : {{cost * quantity}} Rs</p>
<p>Roll No: {{student.rollno}}</p>
Page 3
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
<p>Marks(Math): {{marks[3]}}</p>
</div>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</body>
</html>
Events
AngularJS provides multiple events associated with the HTML controls. For example, ng-click
directive is generally associated with a button. AngularJS supports the following events:
ng-click
ng-dbl-click
ng-mousedown
ng-mouseup
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
ng-keydown
ng-keyup
ng-keypress
ng-change
Example
<input name = "firstname" type = "text" ng-model = "firstName" required>
<input name = "lastname" type = "text" ng-model = "lastName" required>
<input name = "email" type = "email" ng-model = "email" required>
<button ng-click = "reset()">Reset</button>
Page 4
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
<script>
function studentController($scope) {
$scope.reset = function() {
$scope.firstName = "Vamshi";
$scope.lastName = "Krishna";
$scope.email = "[email protected]";
}
$scope.reset();
}
</script>
<body ng-app="">
<h1>KHIT</h1>
<h3>AngularJS Form Validation</h3>
<form name="form1">
<p>Name:
<input name="username"
ng-model="username" required>
<span ng-show=
"form1.username.$pristine && form1.username.$invalid">
The name is required.</span>
</p>
<p>Address:
<input name="useraddress"
ng-model="useraddress" required>
</p>
</form>
<p>
We use the ng-show directive to only
show the error message <br>if the field
Page 5
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
has not modified yet AND content present
in the field is invalid.
</p>
</body>
</html>
Working of Node.js
Node.js accepts the request from the clients and sends the response, while working with the request
node.js handles them with a single thread. To operate I/O operations or requests node.js use the
concept of threads. Thread is a sequence of instructions that the server needs to perform. It runs
parallel on the server to provide the information to multiple clients. Node.js is an event loop single-
threaded language. It can handle concurrent requests with a single thread without blocking it for
one request.
Advantages
Easy Scalability: Easily scalable the application in both horizontal and vertical
directions.
Real-time web apps: Node.js is much more preferable because of faster
synchronization. Also, the event loop avoids HTTP overloaded for Node.js
development.
Fast Suite: NodeJS acts like a fast suite and all the operations can be done quickly
like reading or writing in the database, network connection, or file system
Easy to learn and code: NodeJS is easy to learn and code because it uses JavaScript.
Advantage of Caching: It provides the caching of a single module. Whenever there is
any request for the first module, it gets cached in the application memory, so you
don’t need to re-execute the code.
Page 6
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Node.js Process Model
Traditional web server model
The traditional web server model consists of a pool of threads which process requests. Each
time a new request comes in; it is assigned to a different thread in the pool.
In the event a request is received and a thread is not available, the request will have to wait
until a previous request finishes, a response is returned, and the thread is returned to the thread
pool. In this way, the web server model is synchronous, or blocking.
Page 7
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
The combination of the asynchronous nature of Node.js plus the reduced resource consumption of the
single-threaded process leads to a significant increase in performance. It should be noted, however,
that Node.js does not excel with CPU-intensive operations such as image processing and
computationally-expensive work.
Node JS Modules
Modules in Node.js are blocks of encapsulated code that can be reused throughout your
application. These modules can include functions, objects, and variables that are exported
from the code files.
Every Node.js file can be considered a module that can export code for reuse in other parts
of the application. This modular approach allows developers to separate concerns, reuse
code, and maintain a clean architecture.
At its core, a Node.js module is an object that contains the following key properties:
exports: The object that a module can export for use in other modules.
require(): A function that is used to import modules into other modules.
module: The object that represents the current module.
Types of Node.js
1) Core Modules: Node.js has many built-in modules that are part of the platform and come
with Node.js installation. These modules can be loaded into the program by using
the required function.
Syntax:
const module = require('module_name');
Example
const http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('Welcome to this page!');
res.end();
}).listen(3000);
Page 8
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
2) Local Modules: Unlike built-in and external modules, local modules are created locally in your
Node.js application. Let’s create a simple calculating module that calculates various operations.
Example
// Filename: calc.js
// Filename: index.js
3) Third-party modules: Third-party modules are modules that are available online using the Node
Package Manager(NPM). These modules can be installed in the project folder or globally. Some of
the popular third-party modules are Mongoose, Express, Angular, and React.
Example
Page 9
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
Asynchronous approach: They are called non-blocking functions as it never waits for each
operation to complete, rather it executes all operations in the first go itself. The result of each
operation will be handled once the result is available i.e. each command will be executed soon after
the execution of the previous command. While the previous command runs in the background and
loads the result once it is finished processing the data.
Example
const fs = require("fs");
// Asynchronous - Opening File
console.log("opening file!");
fs.open("input.txt", "r+", function (err, fd) {
if (err) {
return console.error(err); }
console.log("File open successfully");
});
Page 10
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
2) Reading a File: The fs.read() method is used to read the file specified by fd. This method reads
the entire file into the buffer.
Syntax:
fs.read(fd, buffer, offset, length, position, callback)
Example
const fs = require("fs");
const buf = new Buffer(1024);
console.log("opening an existing file");
fs.open("input.txt", "r+", function (err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
console.log("reading the file");
3) Writing to a File: This method will overwrite the file if the file already exists. The fs.writeFile()
method is used to asynchronously write the specified data to a file. By default, the file would be
replaced if it exists. The ‘options’ parameter can be used to modify the functionality of the method.
Syntax:
fs.writeFile(path, data, options, callback)
Example
const fs = require("fs");
console.log("writing into existing file");
fs.writeFile("input.txt", "This is KHIT", 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());
});
});
Page 11
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
4) Appending to a File: The fs.appendFile() method is used to synchronously append the data to the
file.
Syntax:
fs.appendFile(filepath, data, options, callback);
// or
fs.appendFileSync(filepath, data, options);
Example
const fs = require("fs");
let data = "\nLearn Node.js";
// Append data to file
fs.appendFile(
"input.txt", data, "utf8",
// Callback function
function (err) {
if (err) throw err;
// If no error
console.log("Data is appended to file successfully.");
}
);
5) Closing the File: The fs.close() method is used to asynchronously close the given file descriptor
thereby clearing the file that is associated with it. This will allow the file descriptor to be reused for
other files. Calling fs.close() on a file descriptor while some other operation is being performed on
it may lead to undefined behavior.
Syntax:
fs.close(fd, callback)
Example
// Close the opened file.
fs.close(fd, function (err) {
if (err) {
console.log(err); }
console.log("File closed successfully."); });
6) Delete a File: The fs.unlink() method is used to remove a file or symbolic link from the
filesystem. This function does not work on directories, therefore it is recommended to use
fs.rmdir() to remove a directory.
Syntax
fs.unlink(path, callback)
Example
const fs = require("fs");
console.log("deleting an existing file");
fs.unlink("input.txt", function (err) {
if (err) {
return console.error(err);
}
console.log("File deleted successfully!");
});
Page 12
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Node JS URL module
The NodeJS URL module provides us with utilities for the resolution and parsing of the URL. The
URL string is a structured string that contains multiple segments.
Example
URL = "http://user:[email protected]:80/pa/th?q=val#hash".
Where
‘http:’ specifies the protocol segment.
‘user’ specifies the username segment.
‘pass’ specifies the password segment.
‘site.com:80’ specifies the host segment.
‘site.com’ specifies the hostname portion.
‘80’ specifies the port portion.’
‘/pa/th?q=val’ specifies the pathname segment.
‘/pa/th’ specifies the path portion.
‘?q=val’ specifies the search portion.
‘#bar’ specifies the hash segment.
Node JS Events
In Node.js, an event is an action or occurrence that the program can detect and handle. The event-
driven architecture allows asynchronous programming, and your application becomes able to
perform non-blocking operations. This means that while waiting for an operation to complete (like
reading a file or making a network request), the application can continue processing other tasks.
Working of events
Page 13
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
Step 1: Importing the Events Module
To start using events in your application, you need to import the events module and create an
instance of the EventEmitter class.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
Step 2: Registering Event Listeners
You can register listeners for specific events using the on() method. The first argument is the event
name, and the second argument is the callback function to be executed when the event is emitted.
myEmitter.on('event', () => {
console.log('An event occurred!');
});
Step 3: Emitting Events
To trigger an event, use the emit() method with the event name as the first argument.
myEmitter.emit('event'); // Output: An event occurred!
EventEmitter Class
At the core of the Node.js event system is the EventEmitter class. This class allows objects to emit
named events that can be listened to by other parts of your application. It is included in the built-in
events module.
Listening events
Before emitting any event, it must register functions(callbacks) to listen to the events.
Syntax:
eventEmitter.addListener(event, listener)
eventEmitter.on(event, listener)
eventEmitter.once(event, listener)
Removing Listener
The eventEmitter.removeListener() takes two argument event and listener, and removes that
listener from the listeners array that is subscribed to that event.
While eventEmitter.removeAllListeners() removes all the listener from the array which are
subscribed to the mentioned event.
Syntax:
eventEmitter.removeListener(event, listener)
eventEmitter.removeAllListeners([event])
eventEmitter.listeners()
It returns an array of listeners for the specified event.
Syntax:
eventEmitter.listeners(event)
eventEmitter.listenerCount()
It returns the number of listeners listening to the specified event.
Syntax:
eventEmitter.listenerCount(event)
eventEmitter.prependOnceListener()
It will add the one-time listener to the beginning of the array.
Syntax:
Page 14
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
eventEmitter.prependOnceListener(event, listener)
eventEmitter.prependListener()
It will add the listener to the beginning of the array.
Syntax:
eventEmitter.prependListener(event, listener)
Page 15