0% found this document useful (0 votes)
6 views15 pages

WT - Unit 5

The document provides an overview of AngularJS and Node.js, detailing their fundamental concepts, advantages, and functionalities. It covers AngularJS features such as expressions, form validation, and data binding, as well as Node.js's event-driven architecture, process model, and module system. The content serves as a guide for developing web applications using these technologies, including installation steps and code examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views15 pages

WT - Unit 5

The document provides an overview of AngularJS and Node.js, detailing their fundamental concepts, advantages, and functionalities. It covers AngularJS features such as expressions, form validation, and data binding, as well as Node.js's event-driven architecture, process model, and module system. The content serves as a guide for developing web applications using these technologies, including installation steps and code examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Dr.

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.

Fundamentals of Angular JS and NODE JS


Angular JS
 AngularJS is a free and open-source JavaScript framework that helps developers build
modern web applications. It extends HTML with new attributes and it is perfect for single-
page applications (SPAs).
 AngularJS revolutionized front-end development by introducing a Model-View-Controller
(MVC) architecture.
 Model: Represents your application's data and business logic.
 View: Handles the user interface and presentation layer.
 Controller: Acts as the glue, binding the model and view together and handling user
interactions.
 AngularJS is a JavaScript framework written in JavaScript and is distributed as a JavaScript
file, and can be added to a web page with a script tag:
Syntax
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>

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>

Steps to install Angular JS


Step 1: Install the Angular CLI
npm install - g @angular/cli

Step-2: Initialize new project using the below command

Page 1
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297
ng new my-app

Step-3: Go to your project directory


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

<p> Sorting Algorithms:</p>


<ul>
<li>{{ sort.one }}</li>
<li>{{ sort.two }}</li>
<li>{{ sort.three }}</li>
</ul>
</div>
</body>
</html>

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>

Angular JS Form Validation & Form Submission


 AngularJS performs form validation on the client side. AngularJS monitors the state of the
form and input fields (input, text-area, select), and notify the user about the current state.
 Form input fields have the following states:
1) $untouched: It shows that field has not been touched yet.
2) $touched: It shows that field has been touched.
3) $pristine: It represents that the field has not been modified yet.
4) $dirty: It illustrates that the field has been modified.
5) $invalid: It specifies that the field content is not valid.
6) $valid: It specifies that the field content is valid.
 Following directives are generally used to track (validate) errors in an AngularJS form:
1) $pristine: It represents that the fields have not been modified yet.
2) $dirty: It illustrates that one or more fields have been modified.
3) $invalid: It specifies that the form content is not valid.
4) $valid: It specifies that the form content is valid.
5) $submitted: It specifies that the form is submitted.
6) $error - states the exact error.

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>

Example program on Angular JS forms


<!DOCTYPE html>
<html>
<head>
<title>AngularJS Form Validation</title>
<script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
h1 {
color: green;
}
</style>
</head>

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

Node.js- Introduction, Advantages


 Node.js is an open-source, cross-platform JavaScript runtime environment that allows
developers to run JavaScript code on the server side.
 Created by Ryan Dahl in 2009, Node.js has revolutionized server-side programming by
offering an efficient, event-driven, and non-blocking I/O model.
 Key features of Node,js
 JavaScript Runtime: Node.js runs on the V8 JavaScript engine, which is also the
core engine behind Google Chrome.
 Single Process Model: A Node.js application operates within a single process,
avoiding the need to create a new thread for every request.
 Asynchronous I/O: Node.js provides a set of asynchronous I/O primitives in its
standard library. These primitives prevent JavaScript code from blocking, making
non-blocking behavior the norm.
 Concurrency Handling: Node.js efficiently handles thousands of concurrent
connections using a single server. It avoids the complexities of managing thread
concurrency, which can lead to bugs.
 JavaScript Everywhere: Frontend developers familiar with JavaScript can
seamlessly transition to writing server-side code using Node.js.
 ECMAScript Standards: Node.js supports the latest ECMAScript standards. You
can choose the version you want to use, independent of users’ browser updates.

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.

Node.js Process model


 The Node.js process model differs from traditional web servers in that Node.js runs in a single
process with requests being processed on a single thread.
 One advantage of this is that Node.js requires far fewer resources. When a request comes in, it
will be placed in an event queue. Node.js uses an event loop to listen for events to be raised for
an asynchronous job. The event loop continuously runs, receiving requests from the event
queue.
 There are two scenarios that will occur depending on the nature of the request.
1) If the request is non-blocking, it does not involve any long-running processes or data
requests, the response will be immediately prepared and then sent back to the client.
2) In the event the request is blocking, requiring I/O operations, the request will be sent
to a worker thread pool. The request will have an associated call-back function that
will fire when the request is finished and the worker thread can send the request to
the event loop to be sent back to the client.
 In this way, when the single thread receives a blocking request, it hands it off so that the thread
can process other requests in the meantime. In this way Node.js is inherently asynchronous.

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

Core Modules Description

http creates an HTTP server in Node.js.

assert set of assertion functions useful for testing.

fs used to handle file system.

path includes methods to deal with file paths.

provides information and control about the current


process
Node.js process.

Page 8
Dr. Vamshi Krishna K
Associate Professor, Dept. of CSE, KHIT, Guntur
[email protected], 8143260297

Core Modules Description

os provides information about the operating system.

utility used for parsing and formatting URL query


querystring
strings.

module provides utilities for URL resolution and


url
parsing.

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

exports.add = function (x, y) {


return x + y;
};
exports.sub = function (x, y) {
return x - y;
};
exports.mult = function (x, y) {
return x * y;
};
exports.div = function (x, y) {
return x / y;
};

// Filename: index.js

const calculator = require('./calc');


let x = 50, y = 10;
console.log("Addition of 50 and 10 is " + calculator.add(x, y));
console.log("Subtraction of 50 and 10 is " + calculator.sub(x, y));
console.log("Multiplication of 50 and 10 is " + calculator.mult(x, y));
console.log("Division of 50 and 10 is " + calculator.div(x, y));

To run the program


node 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}`);
});

Node JS File system


 The fs (File System) module in Node.js provides an API for interacting with the file system.
It allows you to perform operations such as reading, writing, updating, and deleting files
and directories, which are essential for server-side applications and scripts.
 To handle file operations like creating, reading, deleting, etc., Node.js provides an inbuilt
module called FS (File System).
 All file system operations can have synchronous and asynchronous forms depending upon
user requirements. To use this File System module, use the require() method:
const fs = require('fs');

What is Synchronous and Asynchronous approach?


Synchronous approach: They are called blocking functions as it waits for each operation to
complete, only after that, it executes the next operation, hence blocking the next command from
execution i.e. a command will not be executed until & unless the query has finished executing to
get all the result from previous commands.

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.

Operations of Node.js file system


1) Open file: The fs.open() method is used to create, read, or write a file. The fs.readFile() method
is only for reading the file and fs.writeFile() method is only for writing to the file, whereas
fs.open() method does several operations on a file.
Syntax
fs.open(path, flags, mode, callback)

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

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

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.

Including the URL module


To include the URL module, add the below-given syntax at the beginning of your Node.js document.
Syntax
Const url = require(‘url’);

Printing the serialized URL


To print the given serialized URL, we need to use the NodeJS url.href property.
Example
console.log("The given URL -"); const myURL = new
URL('https://www.khit.com/index.htm');
console.log(myURL.href);

Printing hostname from the URL


To print the hostname segment from the URL, we use the NodeJS url.hostname property.
Example
const myURL = new URL('https://www.khit.com:100/index.htm'); console.log("The URL: " +
myURL.href); console.log("Hostname of the URL: " + myURL.hostname);

Printing the pathname from the URL


To print the pathname segment from the URL, we use the NodeJS url.pathname property.
Example
const myURL = new URL("https://www.khit.com/prime-pack/cloud-computing/index.asp");
console.log("The URL: " + myURL.href); console.log("Pathname of the URL: " +
myURL.pathname);

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

You might also like