Full Stack Notes Final

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

IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

UNIT II NODE JS
Basics of Node JS – Installation – Working with Node packages – Using Node package
manager –Creating a simple Node.js application – Using Events – Listeners –Timers -
Callbacks – Handling Data I/O – Implementing HTTP services in Node.js

Basics of Node.JS
 Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8
Engine).Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36.
 Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and
scalable network applications.
 Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and
efficient, perfect for data-intensive real-time applications that run across distributed
devices.
 Node.js is an open source, cross-platform runtime environment for developing server-side
and networking applications. Node.js applications are written in JavaScript, and can be run
within the Node.js runtime on OS X, Microsoft Windows, and Linux.
 Node.js also provides a rich library of various JavaScript modules which simplifies the
development of web applications using Node.js to a great extent.
Node.js = Runtime Environment + JavaScript Library

Features of Node.JS:
Following are some of the important features that make Node.js the first choice of software
architects.
1.Asynchronous and Event Driven –
 All APIs of Node.js library are asynchronous,that is, non-blocking. It essentially means
a Node.js based server never waits foran API to return data.
 The server moves to the next API after calling it and anotification mechanism of
Events of Node.js helps the server to get a response from the previous API call.
2.Very Fast
 Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in
code execution.

3.Single Threaded but Highly Scalable


S.Yamunadevi AP/IT,PSNACET 1
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
 Node.js uses a single threaded model with event looping. Event mechanism helps the
server to respond in a non-blocking way and makes the server highly scalable as
opposed to traditional servers which create limited threads to handle requests.
 Node.js uses a single threaded program and the same program can provide service to a
much larger number of requests than traditional servers like Apache HTTP Server.
4. No Buffering
 Node.js applications never buffer any data. These applications simply output the data
in chunks.
5. License
 Node.js is released under the MIT license

Who Uses Node.js?


Node.js quickly gained popularity among a wide variety of companies. These companies use
Node.js first and foremost for scalability but also for ease of maintenance and faster
development.
The following are just a few of the companies using the Node.js technology:
 Yahoo!
 LinkedIn
 eBay
 New York Times
 Dow Jones
 Microsoft

What Is Node.js Used For?

Node.js can be used for a wide variety of purposes. Because it is based on V8 and has highly
optimized code to handle HTTP traffic, the most common use is as a webserver. However,
Node.js can also be used for a variety of other web services such as:

 Web services APIs such as REST


 Real-time multiplayer games
 Backend web services such as cross-domain, server-side requests
 Web-based applications
 Multiclient communication such as IM

Installing Node.js

S.Yamunadevi AP/IT,PSNACET 2
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
To easily install Node.js, download an installer from the Node.js website at http://nodejs.org.
The Node.js installer installs the necessary files on your PC to get Node.js up and running. No
additional configuration is necessary to start creating Node.js applications.

The following list describes the executables in the Node.js install location that you need to get
started:
 node: This file starts a Node.js JavaScript VM. If you pass in a JavaScript file location,
Node.js executes that script. If no target JavaScript file is specified,then a script prompt
is shown that allows you to execute JavaScript code directly from the console.
 npm: This command is used to manage the Node.js packages
 node_modules: This folder contains the installed Node.js packages. These packages
act as libraries that extend the capabilities of Node.js.

Creating Node.js Application


Step 1 - Import Required Module
We use the require directive to load the http module and store the returned HTTP instance
into an http variable as follows:
var http = require("http");

Step 2-Create Server


We use the created http instance and call http.createServer() method to create a server
instance and then we bind it at port 8081 using the listen method associated with the server
instance.
Pass it a function with parameters request and response. Write the sample implementation to
always return "Hello World".

http.createServer(function (request, response) {


// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});

// Send the response body as "Hello World"


response.end('Hello World\n');
}).listen(8081);

// Console will print the message


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

S.Yamunadevi AP/IT,PSNACET 3
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
The above code is enough to create an HTTP server which listens, i.e., waits for a request
over 8081 port on the local machine.

Step 3-Testing Request & Response


Let's put step 1 and 2 together in a file called main.js and start our HTTP server as shown
below:

var http = require("http");


http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});

// Send the response body as "Hello World"


response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

Now execute the main.js to start the server as follows:


$ node main.js

Verify the Output. Server has started.


Server running at http://127.0.0.1:8081/

S.Yamunadevi AP/IT,PSNACET 4
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

REPL stands for Read Eval Print Loop and it represents a computer environment like a
Windows console or Unix/Linux shell where a command is entered and the system responds
with an output in an interactive mode. Node.js or Node comes bundled with a REPL
environment. It performs the following tasks:

 Read - Reads user's input, parses the input into JavaScript data-structure, and stores in
memory.
 Eval - Takes and evaluates the data structure.
 Print - Prints the result.
 Loop - Loops the above command until the user presses ctrl-c twice.

The REPL feature of Node is very useful in experimenting with Node.js codes and to debug
JavaScript codes.

REPL Commands

 ctrl + c - terminate the current command.


 ctrl + c twice - terminate the Node REPL.
 ctrl + d - terminate the Node REPL.
 Up/Down Keys - see command history and modify previous commands. ∙ tab Keys -
list of current commands.
 help - list of all commands.
 break - exit from multiline expression.
 clear - exit from multiline expression.
S.Yamunadevi AP/IT,PSNACET 5
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
 save filename - save the current Node REPL session to a file.
 load filename - load file content in current Node REPL session.

Using package.json
 package.json is present in the root directory of any Node application/module and is
used to define the properties of a package. Let's open package.json of express package
present in node_modules/express/
{
"name": "express",
"description": "Fast, unopinionated, minimalist web framework",
"version": "4.11.2",
"author": {
"name": "TJ Holowaychuk",
"email": "[email protected]"
},
"contributors": [
{
"name": "Aaron Heckmann",
"email": "[email protected]"
},
{
"name": "Ciaran Jessup",
"email": "[email protected]"
},
{
"name": "Douglas Christopher Wilson",
"email": "[email protected]"
},
{
"name": "Guillermo Rauch",
"email": "[email protected]"
},
{
"name": "Jonathan Ong",
"email": "[email protected]"
},

Attributes of Package.json

 name - name of the package


 version - version of the package

 description - description of the package


 homepage - homepage of the package

S.Yamunadevi AP/IT,PSNACET 6
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
 author - author of the package
 contributors - name of the contributors to the package
 dependencies - list of dependencies. NPM automatically installs all the dependencies
mentioned here in the node_module folder of the package.
 repository - repository type and URL of the package
 main - entry point of the package
 keywords – keywords

Node.js is a single-threaded application, but it can support concurrency via the concept of
event and callbacks. Every API of Node.js is asynchronous and being single-threaded, they
use async function calls to maintain concurrency. Node uses observer pattern.

Node thread keeps an event loop and whenever a task gets completed, it fires the
corresponding event which signals the event-listener function to execute.

Event-Driven Programming
Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast
compared to other similar technologies. As soon as Node starts its server, it simply initiates its
variables, declares functions, and then simply waits for the event to occur.

In an event-driven application, there is generally a main loop that listens for events, and
then triggers a callback function when one of those events is detected

Although events look quite similar to callbacks, the difference lies in the fact that callback

S.Yamunadevi AP/IT,PSNACET 7
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
functions are called when an asynchronous function returns its result, whereas event handling
works on the observer pattern. The functions that listen to events act as Observers. Whenever
an event gets fired, its listener function starts executing.
Node.js has multiple in-built events available through events module and EventEmitter class
which are used to bind events and event-listeners as follows:

// Import events module


var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

Following is the syntax to bind an event handler with an event:


// Bind event and even handler as follows
eventEmitter.on('eventName', eventHandler);

We can fire an event programmatically as follows:


// Fire an event
eventEmitter.emit('eventName');

Example:Create a js file named main.js with the following code:

// Import events module


var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
// Create an event handler as follows
var connectHandler = function connected() {
console.log('connection successful.');
// Fire the data_received event
eventEmitter.emit('data_received');
}
// Bind the connection event with the handler
eventEmitter.on('connection', connectHandler);
// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function(){
console.log('data received successfully.');
});

// Fire the connection event

eventEmitter.emit('connection');
S.Yamunadevi AP/IT,PSNACET 8
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
console.log("Program Ended.");

Now let's try to run the above program and check its output:
$ mnode main.js

Output:
connection successful.
data received successfully.
Program Ended.

EVENTEMITTER CLASS
EventEmitter class lies in the events module. It is accessible via the following code:

// Import events module


var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

When an EventEmitter instance faces any error, it emits an 'error' event. When a new
listener is added, 'newListener' event is fired and when a listener is removed,
'removeListener' event is fired.

EventEmitter provides multiple properties like on and emit. on property is used to bind a
function with the event and emit is used to fire an event.

EVENT METHODS

addListener(event, listener)
 Adds a listener at the end of the listeners array for the specified event. No checks are
made to see if the listener has already been added.
 Multiple calls passing the same combination of event and listener will result in the
listener being added multiple times. Returns emitter, so calls can be chained.

on(event, listener)
 Adds a listener at the end of the listeners array for the specified event. No checks are
made to see if the listener has already been added.

S.Yamunadevi AP/IT,PSNACET 9
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
 Multiple calls passing the same combination of event and listener will result in the
listener being added multiple times. Returns emitter, so calls can be chained.
once(event, listener)
 Adds a one-time listener to the event. This listener is invoked only the next time the
event is fired, after which it is removed. Returns emitter, so calls can be chained
Node.js
removeListener(event, listener)
 Removes a listener from the listener array for the specified event.
 Caution: It changes the array indices in the listener array behind the listener.
removeListener will remove, at most, one instance of a listener from the listener array.
 If any single listener has been added multiple times to the listener array for the
specified event, then removeListener must be called multiple times to remove each
instance. Returns emitter, so calls can be chained.
removeAllListeners([event])
 Removes all listeners, or those of the specified event. It's not a good idea to remove
listeners that were added elsewhere in the code,
 especially when it's on an emitter that you didn't create (e.g. sockets or file streams).
Returns emitter, so calls can be chained.
setMaxListeners(n)
 By default, EventEmitters will print a warning if more than 10 listeners are added for a
particular event.
 This is a useful default which helps finding memory leaks. Obviously not all Emitters
should be limited to 10.
 This function allows that to be increased. Set to zero for unlimited.

listeners(event)
 Returns an array of listeners for the specified event.
emit(event, [arg1], [arg2], [...])
 Execute each of the listeners in order with the supplied arguments. Returns true if the
event had listeners, false otherwise.

Class Methods

listenerCount(emitter, event)
 Returns the number of listeners for a given event Events
newListener
S.Yamunadevi AP/IT,PSNACET 10
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
 event – String; the event name
 listener – Function; the event handler function This event is emitted any time a listener
is added. When this event is triggered, the listener may not yet have been added to the
array of listeners for the event.
removeListener
 event - String The event name
 listener - Function The event handler function This event is emitted any time someone
removes a listener. When this event is triggered, the listener may not yet have been
removed from the array of listeners for the event.

Example: Creating a custom EventEmitter object and implementing three listeners that are
triggered when the balancedChanged event is triggered

var events = require('events');


function Account() {
this.balance = 0;
events.EventEmitter.call(this);
this.deposit = function(amount)
{
this.balance += amount;
this.emit('balanceChanged');
};
this.withdraw = function(amount){
this.balance -= amount;
this.emit('balanceChanged');
};
}
Account.prototype.__proto__ = events.EventEmitter.prototype;
function displayBalance(){
console.log("Account balance: $%d", this.balance);
}
function checkOverdraw(){

if (this.balance < 0){


console.log("Account overdrawn!!!");
}
}
function checkGoal(acc, goal){
if (acc.balance > goal){
console.log("Goal Achieved!!!");
S.Yamunadevi AP/IT,PSNACET 11
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
}
}
var account = new Account();
account.on("balanceChanged", displayBalance);
account.on("balanceChanged", checkOverdraw);
account.on("balanceChanged", function(){
checkGoal(this, 1000);
});
account.deposit(220);
account.deposit(320);
account.deposit(600);
account.withdraw(1200);

Output:
C:\books\node\ch04>node emmiter_listener.js
Account balance: $220
Account balance: $540
Account balance: $1140
Goal Achieved!!!
Account balance: $-60
Account overdrawn!!!

TIMERS:

The timers module contains functions that can execute code after a certain period of time.You
do not need to import the timer module explicitly, as it is already globally available across the
emulated browser JavaScript API.

Timers module is mainly categorised into two categories

Scheduling Timers − This timer schedules the task to take place after a certain instant of time.

 setImmediate()
 setInterval()
 setTimeout()
Cancelling Timers − This type of timers cancels the scheduled tasks which is set to take
place.
 ClearImmediate()
 clearInterval()
 clearTimeout()
S.Yamunadevi AP/IT,PSNACET 12
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
Scheduling Timers

1. setTimeout() Method

The setTimeout() method schedules the code execution after a designated number of
milliseconds. Only after the timeout has occurred, the code will be executed. The specified
function will be executed only once. This method returns an ID that can be used in
clearTimeout() method.

let str = 'Fullstack-Timers!';

setTimeout(function () {
// Will be printed after 2 seconds
return console.log(str);
}, 2000);

// This will be printed immediately


console.log('Executing setTimeout() method');

Output:

Executing setTimeout() method


Fullstack-Timers!

2. setImmediate() Method
setImmediate() executes the code at the end of the current event loop cycle.

Example

filename - immediate.js

// Setting timeout for the function


setTimeout(function () {
console.log('setTimeout() function running');
}, 5000);

// Running this function immediately before any other


setImmediate(function () {
console.log('setImmediate() function running');
});
S.Yamunadevi AP/IT,PSNACET 13
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
// Directly printing the statement
console.log('Simple statement in the event loop');

Output
Simple statement in the event loop
setImmediate() function running
setTimeout() function running

3. setInterval() Method

setInterval() executes the code after the specified interval. The function is executed multiple
times after the interval has passed. The function will keep on calling until the process is
stopped externally or using code after specified time period.

Example
filename - interval.js
setInterval(function() {
console.log(‘Full stack- SIMPLY LEARNING');
}, 1000);

Output

Full stack- SIMPLY LEARNING


Full stack- SIMPLY LEARNING
Full stack- SIMPLY LEARNING
Full stack- SIMPLY LEARNING
Full stack- SIMPLY LEARNING
Full stack- SIMPLY LEARNING
Full stack- SIMPLY LEARNING

4.clearImmediate() Method

This method clears the Immediate timer object that is created by the setImmediate() method.

Example

filename - clearImmediate.js
// clearImmediate() Example

var timer = setImmediate(function A() {


console.log("Timer set");
});

S.Yamunadevi AP/IT,PSNACET 14
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
clearImmediate(timer);
console.log("Timer cancelled");

Output

Timer cancelled

5.clearInterval() Method

This method clears the Immediate timer object that is created by the setInterval() method.

Syntax

clearInterval(timer)

Example

filename - clearInterval.js
// clearInterval() Example
var si = setInterval(function A() {
return console.log("Setting Intevals for 500 ms !");
}, 500);

// Cleared the interval from 1000 ms


setTimeout(function() {
clearInterval(si);
}, 1000);

Output

Setting Intevals for 500 ms !

6.clearTimeout() Method

This method clears the Immediate timer object that is created by the setTimeout() method.

Syntax

clearTimeout(timerObject)

Example
S.Yamunadevi AP/IT,PSNACET 15
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
filename - clearTimeout.js
// clearTimeout() Example

var timer = setTimeout(function A() {


return console.log("Hello World!");
}, 500);

// timer2 will be executed


var timer2 = setTimeout(function B() {
return console.log("Simple program to execute timeout”
}, 500);
clearTimeout(timer);

Output

Simple program to execute timeout”

CALLBACKS:

Callback is an asynchronous equivalent for a function. A callback function is called at the


completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are
written in such a way that they support callbacks.

For example, a function to read a file may start reading a file and return the control to the
execution environment immediately so that the next instruction can be executed. Once file I/O
is complete, it will call the callback function while passing the callback function, the content
of the file as a parameter. So there is no blocking or wait for File I/O. This makes Node.js
highly scalable, as it can process a high number of requests without waiting for any function
to return results.
Blocking Code Example

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

Full stack web development is the new era of the technological world. It makes the websites
more interactive and user friendly!!!!!

Create a js file named main.js with the following code:

S.Yamunadevi AP/IT,PSNACET 16
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");

Now run the main.js to see the result:


$ node main.js

Output
Full stack web development is the new era of the technological world. It makes the websites
more interactive and user friendly!!!!!
Program Ended

Non-Blocking Code Example


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

Full stack web development is the new era of the technological world. It makes the websites
more interactive and user friendly!!!!!

Update main.js to have the following code:

var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");

Output

Program Ended

Full stack web development is the new era of the technological world. It makes the websites
more interactive and user friendly!!!!!

These two examples explain the concept of blocking and non-blocking calls.

S.Yamunadevi AP/IT,PSNACET 17
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
 The first example shows that the program blocks until it reads the file and then only it
proceeds to end the program.
 The second example shows that the program does not wait for file reading and
proceeds to print "Program Ended" and at the same time, the program without blocking
continues reading the file.
 Thus, a blocking program executes very much in sequence.
 From the programming point of view, it is easier to implement the logic but non-
blocking programs do not execute in sequence.
 In case a program needs to use any data to be processed, it should be kept within the
same block to make it sequential execution.

HANDLING DATA I/O IN NODE.JS

Definition of JSON:

 One of the most common data types that you work with when implementing Node.js
web applications and services is JSON (JavaScript Object Notation).
 JSON is a lightweight method to convert JavaScript objects into a string form and then
back again.
 This provides an easy method when you need to serialize data objects when passing
them from client to server, process to process, stream to stream, or when storing them
in a database.

There are several reasons to use JSON to serialize your JavaScript objects over XML
including the following:
 JSON is much more efficient and takes up fewer characters.
 Serializing/deserializing JSON is faster than XML because it’s simpler syntax.
 JSON is easier to read from a developer’s perspective because it is similar to
JavaScript syntax.
 The only reasons you might want to use XML over JSON are for complex objects or if
you have XML/XSLT transforms already in place.

Converting JavaScript Objects to JSON

Node also allows you to convert a JavaScript object into a properly formatted JSON string.
Thus the string form can be stored in a file or database, sent across an HTTP connection, or
written to a stream/buffer. Use the JSON.stringify(text) method to parse JSON text and
generate a JavaScript object

BUFFERS:
S.Yamunadevi AP/IT,PSNACET 18
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
Buffer class is a global class that can be accessed in an application without importing the
buffer module.

Creating Buffers

Node Buffer can be constructed in a variety of ways.


Method 1
Following is the syntax to create an uninitiated Buffer of 10 octets:
var buf = new Buffer(10);
Method 2
Following is the syntax to create a Buffer from a given array:
var buf = new Buffer([10, 20, 30, 40, 50]);
Method 3
Following is the syntax to create a Buffer from a given string and optionally encoding type:
var buf = new Buffer("Simply Easy Learning", "utf-8");

Though "utf8" is the default encoding, you can use any of the following encodings "ascii",
"utf8", "utf16le", "ucs2", "base64" or "hex".
Writing to Buffers
Syntax
Following is the syntax of the method to write into a Node Buffer:
buf.write(string[, offset][, length][, encoding])
Parameters
Here is the description of the parameters used:
 string - This is the string data to be written to buffer.
 offset - This is the index of the buffer to start writing at. Default value is 0.
 length - This is the number of bytes to write. Defaults to buffer.length.
 encoding - Encoding to use. 'utf8' is the default encoding.

S.Yamunadevi AP/IT,PSNACET 19
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
Return Value
This method returns the number of octets written. If there is not enough space in the
buffer to fit the entire string, it will write a part of the string.
Example
buf = new Buffer(256);
len = buf.write("Simply Easy Learning");
console.log("Octets written : "+ len);

When the above program is executed, it produces the following result:


Octets written : 20

Reading from Buffers


Syntax
Following is the syntax of the method to read data from a Node Buffer:
buf.toString([encoding][, start][, end])
Parameters
Here is the description of the parameters used:
 encoding - Encoding to use. 'utf8' is the default encoding.
 start - Beginning index to start reading, defaults to 0.
 end - End index to end reading, defaults is complete buffer.
Return Value
This method decodes and returns a string from buffer data encoded using the specified
character set encoding.
Example
buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
S.Yamunadevi AP/IT,PSNACET 20
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
buf[i] = i + 97;
}
console.log( buf.toString('ascii'));
// outputs: abcdefghijklmnopqrstuvwxyz
console.log( buf.toString('ascii',0,5));
// outputs: abcde
console.log( buf.toString('utf8',0,5));
// outputs: abcde
console.log( buf.toString(undefined,0,5));
// encoding defaults to 'utf8', outputs abcde

Output:
abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde
Convert Buffer to JSON
Syntax
Following is the syntax of the method to convert a Node Buffer into JSON object:
buf.toJSON()
Return Value
This method returns a JSON-representation of the Buffer instance.
Example
var buf = new Buffer('Simply Easy Learning');
var json = buf.toJSON(buf);
console.log(json);

S.Yamunadevi AP/IT,PSNACET 21
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

Output:
[ 83, 105, 109, 112, 108, 121, 32, 69, 97, 115, 121, 32, 76, 101, 97, 114, 110,105, 110, 103 ]
Concatenate Buffers
Syntax
Following is the syntax of the method to concatenate Node buffers to a single Node Buffer:
Buffer.concat(list[, totalLength])
Parameters
Here is the description of the parameters used:
 list - Array List of Buffer objects to be concatenated.
 totalLength - This is the total length of the buffers when concatenated.
Return Value
This method returns a Buffer instance.
Example
var buffer1 = new Buffer('Happy ');
var buffer2 = new Buffer('Learning');
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3 content: " + buffer3.toString());

Output:
buffer3 content: Happy Learning
Buffer Length
Syntax
buf.length;
Return Value
Returns the size of a buffer in bytes.

S.Yamunadevi AP/IT,PSNACET 22
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

Example
var buffer = new Buffer('PSNACETIT');
//length of the buffer
console.log("buffer length: " + buffer.length);
Output:
buffer length: 10
STREAMS
Streams are objects that let you read data from a source or write data to a destination in
continuous fashion. In Node.js, there are four types of streams:
 Readable - Stream which is used for read operation.
 Writable - Stream which is used for write operation.
 Duplex - Stream which can be used for both read and write operation.
 Transform - A type of duplex stream where the output is computed based on input.
Each type of Stream is an EventEmitter instance and throws several events at different
instance of times. For example, some of the commonly used events are:
 data - This event is fired when there is data is available to read.
 end - This event is fired when there is no more data to read.
 error - This event is fired when there is any error receiving or writing data.
 finish - This event is fired when all the data has been flushed to underlying system.
Reading from a Stream
Create a text file named input.txt having the following content:
Full stack web development is the process of creating, testing and deploying the web
applications!!
Create a js file named main.js with the following code:
var fs = require("fs");
var data = '';
// Create a readable stream
var readerStream = fs.createReadStream('input.txt');
// Set the encoding to be utf8.

S.Yamunadevi AP/IT,PSNACET 23
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

readerStream.setEncoding('UTF8');
// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
data += chunk;
});
readerStream.on('end',function(){
console.log(data);
});
readerStream.on('error', function(err){
console.log(err.stack);
});
console.log("Program Ended");
Output
Program Ended
Full stack web development is the process of creating, testing and deploying the web
applications!!

Writing to a Stream
Create a js file named main.js with the following code:
var fs = require("fs");
var data = 'Simply Easy Learning';
// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');
// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');
// Mark the end of file
writerStream.end();
// Handle stream events --> finish, and error
writerStream.on('finish', function() {
console.log("Write completed.");
});
S.Yamunadevi AP/IT,PSNACET 24
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

writerStream.on('error', function(err){
console.log(err.stack);
});
console.log("Program Ended");
Output
Program Ended
Write completed.
Now open output.txt created in your current directory; it should contain the following:
Simply Easy Learning
Piping the Streams
 Piping is a mechanism where we provide the output of one stream as the input to
another stream.
 It is normally used to get data from one stream and to pass the output of that stream to
another stream.
 There is no limit on piping operations. Now we'll show a piping example for reading
from one file and writing it to another file.

Create a js file named main.js with the following code:


var fs = require("fs");
// Create a readable stream
var readerStream = fs.createReadStream('input.txt');
// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');
// Pipe the read and write operations
// read input.txt and write data to output.txt
readerStream.pipe(writerStream);
console.log("Program Ended");

Output.
Program Ended
Open output.txt created in your current directory; it should contain the following:

S.Yamunadevi AP/IT,PSNACET 25
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

Full stack web development is the process of creating, testing and deploying the web
applications!!

Implementing HTTP services in Node.js


To use the http module in Node.js applications, you first need to understand the
request and response objects.

http.ClientRequest object:
 The ClientRequest object is created internally when you call http.request() when
building the HTTP client.
 This object represents the request while it is in progress to the server. You use the
ClientRequest object to initiate, monitor, and handle the response from the server.
 The ClientRequest implements a Writable stream, so it provides all the functionality of
a Writable stream object.
 For example, you can use the write() method to write to it as well as pipe a Readable
stream into it.

http.ServerResponse Object
 The ServerResponse object is created by the HTTP server internally when a request
event is received.
 It is passed to the request event handler as the second argument. You use the
ServerRequest object to formulate and send a response to the client.
 The ServerResponse implements a Writable stream, so it provides all the functionality
of a Writable stream object.
 For example, you can use the write() method to write to it as well as pipe a Readable
stream into it to write data back to the client.

http.IncomingMessage Object
 The IncomingMessage object is created either by the HTTP server or the HTTP client.
 On the server side, the client request is represented by an IncomingMessage object,
and on the client side the server response is represented by an IncomingMessage
object.
 The IncomingMessage object can be used for both because the functionality is
basically the same.

S.Yamunadevi AP/IT,PSNACET 26
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

 The IncomingMessage implements a Readable stream, allowing you to read the client
request or server response as a streaming source.
 This means that the readable and data events can be listened to and used to read data
from the stream.
http.Server Object
 The Node.js HTTP Server object provides the fundamental framework to implement
HTTP servers.
 It provides an underlying socket that listens on a port and handles receiving requests
and then sends responses out to client connections.
 While the server is listening, the Node.js application will not end.

Example:Implementing an HTTP web service that connects remotely to an external source for
weather data

var http = require('http');


var url = require('url');
var qstring = require('querystring');
var APIKEY = ""//place your own api key within the quotes;
function sendResponse(weatherData, res){
var page = '<html><head><title>External Example</title></head>' +
'<body>' +
'<form method="post">' +
'City: <input name="city"><br>' +
'<input type="submit" value="Get Weather">' + '</form>';
if(weatherData){
page += '<h1>Weather Info</h1><p>' + weatherData +'</p>';
}
page += '</body></html>';
res.end(page);
}
function parseWeather(weatherResponse, res) {
var weatherData = '';
weatherResponse.on('data', function (chunk) {
weatherData += chunk;
});
weatherResponse.on('end', function () {
sendResponse(weatherData, res);
});
}
function getWeather(city, res){
city = city.replace(' ', '-');
console.log(city);
S.Yamunadevi AP/IT,PSNACET 27
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

var options = {
host: 'api.openweathermap.org',
path: '/data/2.5/weather?q=' + city + '&APPID=' + APIKEY
};
http.request(options, function(weatherResponse){
parseWeather(weatherResponse, res);
}).end();
}
http.createServer(function (req, res) {
console.log(req.method);
if (req.method == "POST"){
var reqData = '';
req.on('data', function (chunk) {
reqData += chunk;
});
req.on('end', function() {
var postParams = qstring.parse(reqData);
getWeather(postParams.city, res);
});
} else {
sendResponse(null, res);
}
}).listen(8080);

OUTPUT:

S.Yamunadevi AP/IT,PSNACET 28
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

S.Yamunadevi AP/IT,PSNACET 29
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

UNIT III MONGO DB

Understanding NoSQL and MongoDB – Building MongoDB Environment – User accounts – Access
control – Administering databases – Managing collections – Connecting to MongoDB from Node.js –
simple applications

MongoDB:

MongoDB is a cross-platform, document oriented database that provides, high performance, high
availability, and easy scalability. MongoDB works on concept of collection and document.

 MongoDB is an open source NoSQL database management program


 Name derived from Humongous
 Data are stored in the format of JSON
 In MongoDB It stores the data as BSON documents
 JSON is a lightweight format for storing and transporting data
 JSON is often used when data is sent from a server to a web page

Database

Database is a physical container for collections. Each database gets its own set of files on the file
system. A single MongoDB server typically has multiple databases.

Document

A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that
documents in the same collection do not need to have the same set of fields or structure, and common
fields in a collection's documents may hold different types of data.

The following table shows the relationship of RDBMS terminology with MongoDB.

Difference between NoSQL and MongoDB

M MongoDB ONGO DB MySQL MYSQL


MongoDB is an open-source database MySQL is a popular open-source relational
developed by MongoDB, Inc. database management system (RDBMS)
MongoDB stores data in JSON Stores data in the form of tables
individual records are stored as ‘documents’. individual records are stored as ‘rows’ in a
table.
Documents belonging to a particular class or A ‘table’ is used to store rows (records) of
S.Yamunadevi AP/IT,PSNACET
1
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

group as stored in a ‘collection’. similar type.


MongoDB is what is called a NoSQL MySQL as the name suggests uses Structured
database. Query Language (SQL) for database access.
It has a dynamic schema The schema can not be changed

Advantages of MongoDB over RDBMS

 Schema less: MongoDB is a document database in which one collection holds different
documents. Number of fields, content and size of the document can differ from one document to
another.
 Structure of a single object is clear.
 No complex joins.
 Deep query-ability. MongoDB supports dynamic queries on documents using a document-based
query language that's nearly as powerful as SQL.
 Ease of scale-out: MongoDB is easy to scale.
 Conversion/mapping of application objects to database objects not needed.

Why Use MongoDB?

 Document Oriented Storage: Data is stored in the form of JSON style documents.
 Index on any attribute
 Replication and high availability
 Auto-sharding
 Rich queries
 Fast in-place updates
 Professional support by MongoDB

Applications of MongoDB

 Big Data
 Content Management and Delivery
 Mobile and Social Infrastructure
 User Data Management

Install MongoDB on Windows

To install MongoDB on Windows, first download the latest release of MongoDB

From http://www.mongodb.org/downloads. Make sure you get correct version of MongoDB

depending upon your Windows version. To get your Windows version, open command prompt and
execute the following command.

C:\>wmic os get os architecture


OSArchitecture
64-bit
C:\>

S.Yamunadevi AP/IT,PSNACET
2
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

32-bit versions of MongoDB only support databases smaller than 2GB and suitable only for testing and
evaluation purposes.

Now extract your downloaded file to c:\ drive or any other location. Make sure the name of the extracted
folder is mongodb-win32-i386-[version] or mongodb-win32-x86_64-[version].

Here [version] is the version of MongoDB download.

Next, open the command prompt and run the following command.

C:\>move mongodb-win64-* mongodb


1 dir(s) moved.
C:\>

In case you have extracted the MongoDB at different location, then go to that path by using command
cd FOOLDER/DIR and now run the above given process.

MongoDB requires a data folder to store its files. The default location for the MongoDB data directory
is c:\data\db.

So you need to create this folder using the Command Prompt. Execute the following command
sequence.

C:\>md data
C:\md data\db

If you have to install the MongoDB at a different location, then you need to specify an alternate path for
\data\db by setting the path dbpath in mongod.exe.
For the same, issue the following commands.

In the command prompt, navigate to the bin directory present in the MongoDB installation folder.
Suppose my installation folder is D:\set up\mongodb

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"

This will show waiting for connections message on the console output, which indicates that the
mongod.exe process is running successfully.

Now to run the MongoDB, you need to open another command prompt and issue the following
command.

D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
S.Yamunadevi AP/IT,PSNACET
3
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

connecting to: test


>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>

This will show that MongoDB is installed and run successfully. Next time when you run MongoDB,
you need to issue only commands.

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"


D:\set up\mongodb\bin>mongo.exe

Next install the MongoDB by using the following command −


apt-get install mongodb-10gen=2.2.3
In the above installation, 2.2.3 is currently released MongoDB version. Make sure to install the latest
version always. Now MongoDB is installed successfully.

Start MongoDB
sudo service mongodb start

Stop MongoDB
sudo service mongodb stop

Restart MongoDB
sudo service mongodb restart

To use MongoDB run the following command.


mongo
This will connect you to running MongoDB instance.
MongoDB Help
The use Command MongoDB use DATABASE_NAME is used to create database.
The command will create a new database if it doesn't exist, otherwise it will return the existing database.

Syntax
Basic syntax of use DATABASE statement is as follows:
use DATABASE_NAME

Example
If you want to create a database with name <mydb>, then use DATABASE statement would be as
follows:
>use mydb
S.Yamunadevi AP/IT,PSNACET
4
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

switched to db mydb
To check your currently selected database, use the command db
>db mydb
If you want to check your databases list, use the command show dbs.

>show dbs
local 0.78125GB
test 0.23012GB

Your created database (mydb) is not present in list. To display database, you need to insert at least one
document into it.

>db.movie.insert({"name":"sample_db"})
>show dbs
local 0.78125GB
mydb 0.23012GBtest 0.23012GB

In MongoDB default database is test. If you didn't create any database, then collections will be stored in
test database
The dropDatabase() Method
MongoDB db.dropDatabase() command is used to drop a existing database.

Syntax
Basic syntax of dropDatabase() command is as follows:
db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will delete default
'test' database.

Example
First, check the list of available databases by using the command, show dbs.

>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>
If you want to delete new database <mydb>, then dropDatabase() command would be as follows:

>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>
S.Yamunadevi AP/IT,PSNACET
5
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

Now check list of databases.

>show dbs
local 0.78125GB
test 0.23012GB>
─ Drop Database

MongoDB Shell commands

The MongoDB shell provides several commands that can be executed from the shell prompt.

The following list describes each command and its purpose:

help <option>: Displays syntax help for MongoDB shell commands. The option argument allows you
to specify an area where you want help.

use <database>: Changes the current database handle. Database operations are processed on the current
database handle.

db.help: Displays help options for the database methods.

show <option>: Shows a list based on the option argument.

The value of option can be:

dbs: Displays a list of databases.

collections: Displays a list of collections for the current database.

profile: Displays the five most recent system.profile entries taking more than 1 millisecond.

databases: Displays a list of all available databases.

roles: Displays a list of all roles for the current database, both built-in and user-defined.

users: Displays a list of all users for that database.

exit: Exits the database.

MongoDB Shell Methods

The following list provides a few examples of shell methods:

load(script): Loads and runs a JavaScript file inside the shell. This is a great way to script operations
for the database.

UUID(string): Converts a 32-byte hex string into a BSON UUID.

db.auth(username, password): Authenticates you to the current database.

S.Yamunadevi AP/IT,PSNACET
6
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

USER ACCOUNTS:
MongoDB provides the ability to add, remove, and configure users from the MongoDB shell

Listing Users
User accounts are stored in the db.system.users collection of each database. The user object contains
_id, user, pwd, roles, and sometimes other DB Roles fields. The following commands show changing to
the admin database and listing users, as shown in Figure.

use admin

show users

You can also use a query such as find on the db.system.users collection. The difference is that
db.system.users.find() returns a cursor object that you can use to access the User documents.

For example, the following code gets a cursor for users in the admin database and returns the count of
users:

use admin

cur = db.system.users.find()

cur.count()

Creating User Accounts

You can use the MongoDB shell to create user accounts that can administer, read,and write to the
databases. User accounts are added using the createUser() method inside the MongoDB shell.

S.Yamunadevi AP/IT,PSNACET
7
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

The createUser() method accepts a document object that allows you to specify the username, roles, and
password that apply to that user.

Database roles that can be assigned to user accounts

Role Description
read Allows the user to read data from any collection within the
database.

readAnyDatabase Same as read except on the local and config databases.


readWrite Provides all the functionality of read and allows the user to
write to any collection within the database, including
inserting, removing, and updating documents as well as
creating, renaming, and dropping
collections.

readWriteAnyDatabase Same as readWrite except on the local and config databases.


dbAdmin Allows the user to read from and write to compact, get
statistics profile, and perform validations.
dbAdminAnyDatabase Same as dbAdmin except for all databases.
clusterAdmin Allows the user to generally administer MongoDB,
including connections,clustering, replication listing
databases,creating databases, and deleting databases.
userAdmin Allows the user to create and modify user accounts on the
database.
userAdminAnyDatabase Same as userAdmin except on the local and config
databases.

Example:
use test
db.createUser( { user: "testUser",
pwd: "test",
roles: [ "readWrite", "dbAdmin" ] } )

Removing Users
Synatax: removeUser(<username>)method.

Example
use testDB
db.removeUser("testUser")

S.Yamunadevi AP/IT,PSNACET
8
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

ADMINISTERING DATABASES:

The core administration documents address strategies and practices used in the operation of MongoDB
systems and deployments.

Operational Strategies –Higher level documentation of key concepts for the operation and
maintenance of MongoDB deployments.

MongoDB Backup Methods – Describes approaches and considerations for backing up a MongoDB
database.

Monitoring for MongoDB – An overview of monitoring tools, diagnostic strategies, and approaches to
monitoring replica sets and sharded clusters.

Run-time Database Configuration – Outlines common MongoDB configurations and examples of


best-practice configurations for common use cases.

Data Management – Core documentation that addresses issues in data management, organization,
maintenance, and lifecycle management.

Data Center Awareness – Presents the MongoDB features that allow application developers and
database administrators to configure their deployments to be more data center aware or allow
operational and location-based separation.

Capped Collections – Capped collections provide a special type of size-constrained collections that
preserve insertion order and can support high volume inserts.

Ex:db.createCollection("student", {capped:true, size:10000, max:4})

MANAGING COLLECTION:

Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection


exists within a single database. Collections do not enforce a schema. Documents within a collection can
have different fields. Typically, all documents in a collection are of similar or related purpose.

S.Yamunadevi AP/IT,PSNACET
9
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

Rules to be followed while declaring collection:

 Need not define column and data type while creating a collection.
 Collection name starts with name or namespace, and it can have any numbers.
 The collection name should not exceed 128 characters.
 By using (.), the collection gets organized into groups.
 We can create any number of collections in the database.
 First create a database to store the collection value.

Create database to store collection:

USE<"database name">

No.of ways to create collection:

create.collection_name (<document>)

Db. Create collection(name,options)

Example: Create a database for Hospital

use hospital

Collection-1

db.create patient()

db.patient.insert({name:'akash',age:23,reason:'fever'})

db.patient.insert(

{name:'megha',age:24,reason:'fever'},

{name:'rohit',age:25,reason:'cuff'}

Collection-2

db.patienthistory.insert({name:'rupali',age:34,

experience:12})

Delete a collection

db.patienthistory.drop()

Display the collections

show collections

S.Yamunadevi AP/IT,PSNACET
10
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

CONNECTING TO MONGODB FROM NODE.JS

Using a MongoClient object to connect to MongoDB involves creating an instance of the client, opening
a connection to the database, authenticating to the database if necessary, and then handling logout and
closure as needed.
To connect to MongoDB via a MongoClient object, first create an instance of the MongoClient object
using the following syntax:
var client = new MongoClient();
After you have created the MongoClient, you still need to open a connection to the MongoDB server
database using the connect(url, options,callback) method
mongodb://[username:password@]host[:port][/[database][?options]]
For example, to connect to a MongoDB database named MyDB on a host named MyDBServer on port
8088, you would use the following URL:
client.connect('mongodb://MyDBServer:8088/MyDB');
MongoClient connection url components

Option Description
mongodb :// Specifies that this string is using a MongoDB connection
format
username (Optional) Specifies the user name to use when authenticating.
password (Optional) Specifies the password to use when authenticating.
host Specifies the host name or address of the MongoDB server. You
can specify multiple host:port combinations to connect to
multiple MongoDB servers by separating them by a comma. For
example: mongodb://host1:270017,host2:27017,host3:2
port Specifies the port to use when connecting to the MongoDB
server. Default is 27017.
database Specifies the database name to connect to. Default is admin.
options Specifies the key/value pairs of options to use when
connecting. These same options can be specified in the dbOpt
and serverOpt

For example, the following code shows connecting to MongoDB with a reconnect interval of 500 and a
connection timeout of 1000 milliseconds:

client.connect ('mongodb://MyDBServer:8088/MyDB',

{ connectTimeoutMS: 1000,

reconnectInterval: 500 },

function(err, db){ . . . });

S.Yamunadevi AP/IT,PSNACET
11
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT

Connecting to MongoDB using a connection url


var MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
var client = new MongoClient();
client.connect('mongodb://dbadmin:test@localhost:27017/testDB',
{ poolSize: 5, reconnectInterval: 500 },
function(err, db) {
if (err){
console.log("Connection Failed Via Client Object.");
} else {
console.log("Connected Via Client Object . . .");
db.logout(function(err, result) {
if(!err){
console.log("Logged out Via Client Object . . .");
}
db.close();
console.log("Connection closed . . .");
});
}

S.Yamunadevi AP/IT,PSNACET
12
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

UNIT IV
Implementing Express in Node.js - Configuring routes - Using Request and Response objects -
Angular - Typescript - Angular Components - Expressions - Data binding - Built-in directives

IMPLEMENTING EXPRESS IN NODE.JS:

It is simple to start using Express in your Node.js projects. All you need to do is add the express
module using the following command from the root of your project:
npm install express
You can also add express to your package.json module to ensure that express is installed when you
deploy your application. Once you have installed express, you need to create an instance of the express
class to act as the HTTP server for your Node.js application. The following lines of code import the
express module and create an instance of express that you can use:
var express = require('express');
var app = express();

Starting the Express Server To begin implementing Express as the HTTP server for your Node.js
application, you need to create an instance and begin listening on a port. The following three lines of
code start a rudimentary Express server listening on port 8080:
var express = require('express');
var app = express(); app.listen(8080);

Example code to Implementing HTTP and HTTPS servers using Express:

var express = require('express');


var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {host: '127.0.0.1',
key: fs.readFileSync('ssl/server.key'),
cert: fs.readFileSync('ssl/server.crt')
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
app.get('/', function(req, res){
res.send('Hello from Express');
});
CONFIGURING ROUTES:

A route is simply a definition that describes how to handle the path portion of the URI in the HTTP
request to the Express server.

There are two parts when defining the route. First is the HTTP request method (typically GET or
POST). The express module provides a series of functions that allow you to implement routes for the
Express server. These functions all use the following syntax:

S.YAMUNADEVI AP/IT 1
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

app.(path, [callback . . .], callback)


The <method> portion of the syntax actually refers to the HTTP request method, such as GET or
POST.
For example, the following code implements some basic GET and POST routes:
app.get('/', function(req, res){
res.send("Server Root");
});
app.get('/login', function(req, res){
res.send("Login Page");
});
app.post('/save', function(req, res){
res.send("Save Page");
});
When the Express server receives an HTTP request, it looks for a route that has been defined for the
appropriate HTTP method and path. If one is found, a Request and Response object is created to
manage the request and is passed into the callback function(s) for the route.

Applying Parameters in Routes

There are four main methods for implementing parameters in a route:


Query string: Uses the standard ?key=value&key=value... HTTP query string after the path in the
URL. This is the most common method for implementing parameters, but the URLs can become long
and convoluted.
POST params: When implementing a web form or other POST request, you can pass parameters in
the body of the request.
regex: Defines a regular expression as the path portion of the route. Express uses the regex to parse the
path of the URL and store matching expressions as an array of parameters.
Defined parameter: Defines a parameter by name using :<param_name> in the path portion of the
route. Express automatically assigns that parameter a name when parsing the path

Implementing route parameters in express:

var express = require('express');


var url = require('url');
var app = express();
app.listen(80);
app.get('/', function (req, res) {
res.send("Get Index");
});
app.get('/find', function(req, res){
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var response = 'Finding Book: Author: ' + query.author + ' Title: ' + query.title;
console.log('\nQuery URL: ' + req.originalUrl);
console.log(response);
res.send(response);
});

S.YAMUNADEVI AP/IT 2
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

app.get(/^\/book\/(\w+)\:(\w+)?$/, function(req, res){


var response = 'Get Book: Chapter: ' + req.params[0] +' Page: ' + req.params[1];
console.log('\nRegex URL: ' + req.originalUrl);
console.log(response);
res.send(response);
});
app.get('/user/:userid', function (req, res) {
var response = 'Get User: ' + req.param('userid');
console.log('\nParam URL: ' + req.originalUrl);
console.log(response);
res.send(response);
});
app.param('userid', function(req, res, next, value){
console.log("\nRequest received with userid: " + value);
next();
});
Output:

USING REQUEST AND RESPONSE OBJECTS:

Request Objects
The route handlers are passed a Request object as the first parameter. The Request object provides the
data and metadata about the request, including the URL, headers, query string, and much more

Properties and methods of the HTTP Request object:

Request objects Description


originalUrl The original URL string of the request. protocol The protocol string, for
example, http or https.

S.YAMUNADEVI AP/IT 3
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

ip IP address of the request


path Path portion of the request URL.
hostname Hostname of the request.
method HTTP method. GET, POST, etc.
query Query string portion of the request URL.
fresh A Boolean that is true when last-modified matches the current
stale A Boolean that is false when last-modified matches.
secure A Boolean that is true when a TLS connection is established.
acceptsCharset(charset) Returns true if the character set specified by charset is supported.
get(header) Returns the value of the header.
Accessing properties of the Request object in Express:
var express = require('express');
var app = express();
app.listen(80);
app.get('/user/:userid', function (req, res) {
console.log("URL:\t " + req.originalUrl);
console.log("Protocol: " + req.protocol);
console.log("IP:\t " + req.ip);
console.log("Path:\t " + req.path);
console.log("Host:\t " + req.host);
console.log("Method:\t " + req.method);
console.log("Query:\t " + JSON.stringify(req.query));
console.log("Fresh:\t " + req.fresh);
console.log("Stale:\t " + req.stale);
res.send(“UserRequest”);
});
Output:

Response objects

The Response object passed to the route handler provides the necessary functionality to build and send
a proper HTTP response.The most commonly used methods are get(header) and set(header, value),
which gets and sets any header value.

S.YAMUNADEVI AP/IT 4
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

var oldType = res.get('Content-Type');


res.set('Content-Type', 'text/plain');
Properties and methods of the HTTP Response object:
Methods Description
get(header) Returns the value of the header specified.
set(header, value) Sets the value of the header.
set(headerObj) Accepts an object that contains multiple 'header':'value' properties.
Each of the headers in the headerObj is set in the Response object.
location(path) Sets the location header to the path specified. The path can be a URL
path such as /login, a full URL such as http://server.net/, a relative path
such as ../users, or a browser action such as back.
type(type_string) Sets the Content-Type header based on the type_string parameter. The
type_string parameter can be a normal content type such as
application/json, a partial type such as png, or it can be a file extension
such as .html.
attachment([filepath]) Sets the Content-Disposition header to attachment, and if a filepath is
specified the Content-Type header is set based on the file extension.

Sending status, headers, and response data using the Response object
var express = require('express');
var url = require('url');
var app = express();
app.listen(80);
app.get('/', function (req, res) {
var response = '<html><head><title>Simple Send</title></head>' +'<body><h1>Hello from
Express</h1></body></html>';
res.status(200);
res.set({'Content-Type': 'text/html', 'Content-Length': response.length});
res.send(response);
console.log('Response Finished? ' + res.finished);
console.log('\nHeaders Sent: ');
console.log(res.headerSent);
});
app.get('/error', function (req, res) {
res.status(400);
res.send("This is a bad request.");
});

S.YAMUNADEVI AP/IT 5
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

ANGULAR:
 Angular is a javascript framework for building single-page client applications using HTML and
TypeScript.
 Angular is written in TypeScript, supported and developed by Google.
Framework:
 Framework is platform for developing a software applications
 Framework can have in build classes and functions that provides APIs for performing
operations
 It can be reused to add several functionalities
Single page Application:
 A single page application is a website or web application that dynamically rewrites a current
web page with new data
 It doesn‟t require for a web browser loading entire new pages.
 Examples like Gmail, Google Maps, Netflix etc.
Features of an angular:
1. Document Object Model
DOM (Document Object Model) treats an XML or HTML document as a tree structure in which each
node represents a part of the document.

Angular uses regular DOM. Consider that ten updates are made on the same HTML page. Instead of
updating the ones that were already updated, Angular will update the entire tree structure of HTML
tags.

2. TypeScript
 TypeScript defines a set of types to JavaScript, which helps users write JavaScript code that is
easier to understand.
 All of the TypeScript code compiles with JavaScript and can run smoothly on any platform.

S.YAMUNADEVI AP/IT 6
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

 TypeScript is not compulsory for developing an Angular application.


 However, it is highly recommended as it offers better syntactic structure—while making the
codebase easier to understand and maintain.
3.Data Binding
 Data binding is a process that enables users to manipulate web page elements through a web
browser. It employs dynamic HTML and does not require complex scripting or programming.
 Data binding is used in web pages that include interactive components, such as calculators,
tutorials, forums, and games.
 It also enables a better incremental display of a web page when pages contain a large amount of
data.
 Angular uses the two-way binding. The model state reflects any changes made in the
corresponding UI elements.
 Conversely, the UI state reflects any changes in the model state. This feature enables the
framework to connect the DOM to the model data through the controller.

Angular Architecture:
Angular is a full-fledged model-view-controller (MVC) framework. It provides clear guidance on how
the application should be structured and offers bi-directional data flow while providing real DOM.

1.Modules

 An Angular app has a root module, named AppModule, which provides the bootstrap
mechanism to launch the application.

2. Components

Each component in the application defines a class that holds the application logic and data. A
component generally defines a part of the user interface (UI).

3. Templates

The Angular template combines the Angular markup with HTML to modify HTML elements before
they are displayed. There are two types of data binding:

S.YAMUNADEVI AP/IT 7
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Event binding: Lets your app respond to user input in the target environment by updating your
application data.

Property binding: Enables users to interpolate values that are computed from your application data into
the HTML.

4. Metadata

Metadata tells Angular how to process a class. It is used to decorate the class so that it can configure
the expected behavior of a class.

5. Services

When you have data or logic that isn‟t associated with the view but has to be shared across
components, a service class is created. The class is always associated with the @Injectible decorator.

6. Dependency Injection

This feature lets you keep your component classes crisp and efficient. It does not fetch data from a
server, validate the user input, or log directly to the console. Instead, it delegates such tasks to the
services.

TYPESCRIPT:

TypeScript
 Typescript is an open-source object-oriented programing language.
 It is a superset of JavaScript
 It contains all elements of the JavaScript.
 It is a language designed for large-scale JavaScript application development, which can be
executed on any browser, any Host, and any Operating System.
The TypeScript is a language as well as a set of tools.
Typescript components
 Fields: It is a variable declared in a class.
 Methods: It represents an action for the object.
 Constructors: It is responsible for initializing the object in memory.
 Nested class and interface: It means a class can contain another class.
Data Types in Typescript:
TypeScript uses data types to handle data, but there are some differences in syntax. TypeScript also
adds in an extra type enumeration. The following list goes over the types and variables and their syntax
for TypeScript:
String:
 This data type stores character data as a string.
 The character data is specified by either single or double quotation marks.
 All the data contained in the quotes will be assigned to the string variable.

S.YAMUNADEVI AP/IT 8
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Consider these examples:


var myString: string = 'Some Text';
var anotherString: string = "Some More Text";
Number:
 This data type stores data as a numeric value.
 Numbers are useful in counting, calculations, and comparisons.
Here are some examples:
var myInteger: number = 1;
var cost: number = 1.33;
Boolean:
 This data type stores a single bit that is either true or false.
 Booleans are often used for flags.
var yes: boolean = true;
var no: boolean = false;
Array:
 An indexed array is a series of separate distinct data items, all stored under a single variable
name.
 Items in the array can be accessed by their zerobased index, using array[index].
 The following are two examples of creating a simple array and then accessing the first element,
which is at index 0:
var arr:string[] = ["one", "two", "three"];
var firstInArr = arr[0];
var arr2:Array<number> = ["a", "second", "array"];
var firstInArr2 = arr[0];
Null:
 Sometimes you do not have a value to store in a variable, either because it hasn‟t been created
or you are no longer using it.
 At such a time, you can set a variable to null.
 Using null is better than assigning a value of 0 or an empty string ("") because those may be
valid values for the variable.
var newVar = null;
Any:
 In TypeScript you may not always know what type of variable you will be getting or using.
 In such a case, you can assign the variable type as any to allow any other type to be assigned to
a variable.

S.YAMUNADEVI AP/IT 9
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

The following is an example of assigning multiple types to the same variable:


Var anyType: any = "String Assigned";
Var anyType = 404;
Var anyType = True;
Void:
 You use void when you don‟t want a variable to have any type at all.
 In TypeScript, using void prohibits you from assigning or returning a value.
 In most cases you use void when declaring a function you don‟t want to have a return value.
Example:
function empty(): void { document.write("code goes here"); }
Enum:
 TypeScript lets us use enum, which allows you to give names to enumerated values.
The following is the syntax to declare enum:
Enum People {Bob, John, Alex}
Also, to reference the values in enum, you use this syntax:
var x = People.Bob
or this:
var y = People[0]
By using this syntax, you set var x equal to the number 0 and var y equal to the string Bob.
ANGULAR COMPONENTS:
 Angular components are the building blocks you use to create Angular applications.
 Angular components allow you to build self-contained UI elements for an application.
 An Angular component consists of two main parts: the definition in the decorator section and
the class section, which defines the logic.
 The decorator section is used to configure the component, including things like the selector
name and HTML template.
The following list includes some of the most important options available:
Selector: This option allows you to define the HTML tag name used to add the component to the
application via HTML .
Template: This option allows you to add inline HTML to define the look of the component. This is for
when there won‟t be very much code to add, and it‟s helpful for when you don‟t want extra files.
TemplateUrl: This option allows you to import an external template file rather than inline HTML.
This is helpful for separating a large amount of HTML code out of a component to help with
maintainability.

S.YAMUNADEVI AP/IT 10
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Styles: This option allows you to add inline CSS to your component. Use it when only minor style
changes are needed.
StylesUrls: This option allows you to import an array of external CSS
Stylesheet(s). You should use this rather than styles when importing external CSS files.
ViewProviders: This is an array of dependency injection providers. It allows you to import and use
Angular services that provide application functionality such as HTTP communications.
Example:1 A Simple Angular Template and Styling to Display a <span> Element
import { Component } from '@angular/core';@Component
({
selector: 'app-root',
template: `
<span>Hello my name is Brendan</span>`,
styles:[`span {
font-weight: bold;
border: 1px ridge blue;
padding: 5px;} `]
})
export class AppComponent {
title = 'Chapter 22 Intro';
}
Output:

Example 2 :The following example shows that sample table using Angular component.

Component.ts:
import { Component } from "@angular/core"; @Component({
selector: „Example-1',
templateUrl: 'app/app.component.html'

S.YAMUNADEVI AP/IT 11
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

})
export class AppComponent {
name: string = "Karthik"
}
App.component.html

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<h1>This is {{name}} Home Page</h1>
</body>
</html>
Output:

Example:3 inner.component.ts: The Nested Component

import {Component} from '@angular/core';@Component({selector: 'nested',template: `

<span>Congratulations I'm a nested component</span> `,

styles: [` span{

color: #228b22;} `]})

Export class Inner Component{}

S.YAMUNADEVI AP/IT 12
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Example-4 A Component that Takes Data through Its Selector to Modify What Is Displayed via
HTML
import {Component, Input} from '@angular/core';
@Component ({
selector: "myInput",
template: `
<div>
Name: {{personName}}
<br />
Job: {{occupation}}
</div>`,
styles: [` div {
margin: 10px;
padding: 15px;
border: 3px solid grey;} `]
})
export class myInputs {
@Input('name') personName: string;
@Input('occupation') occupation: string;
constructor() {
this.personName = "John Doe";
this.occupation = "Anonymity"
}}
Output:

S.YAMUNADEVI AP/IT 13
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

EXPRESSIONS:

Using expressions is the simplest way to represent data from a component in an Angular view.
Expressions are encapsulated blocks of code inside brackets, like this:
{{expression}}
The Angular compiler compiles an expression into HTML elements so that theresults of the expression
are displayed. For example, look at the following expressions:
{{1+5}}
{{'One' + 'Two'}}
Based on these expressions, the web page displays the following values:
6
OneTwo
Direct declaration of the name and score values in the template expressions, as shown here:
Name: {{name}}
Score: {{score}}
Adjusted: {{score+5}}
Angular expressions are similar to TypeScript/JavaScript expressions in several ways, but they differ
in these ways:
Attribute evaluation: Property names are evaluated against the component model instead of against
the global JavaScript namespace.
More forgiving: Expressions do not throw exceptions when they encounter undefined or null variable
types; instead, they treat them as having no value.
No flow control: Expressions do not allow the following:
 Assignments (for example, =, +=, -=)
 The new operator
 Conditionals
 Loops
 Increment and decrement operators (++ and --)
 Also, you cannot throw an error inside an expression
Example: Basic Strings and Numbers with Simple Math Operations in an Angular Template
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>Expressions</h1>
Number:<br>
{{5}}<hr>
String:<br>

S.YAMUNADEVI AP/IT 14
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

{{'My String'}}<hr>
Adding two strings together:<br>
{{'String1' + ' ' + 'String2'}}<hr>
Adding two numbers together:<br>
{{5+5}}<hr>
Adding strings and numbers together:<br>
{{5 + '+' + 5 + '='}}{{5+5}}<hr>
Comparing two numbers with each other:<br>
{{5= = 5 }}<hr>‟
})
Export class App component{}

Output:

DATA BINDING:

 Data binding is the process of linking data from a component with what is displayed in a web
page.
 When data in the component changes, the UI rendered to the user is automatically updated.
 Angular provides a very clean interface to link the model data to elements in a web page.
There are many ways in Angular to use data binding to make an application look andact in different
ways.
 Interpolation: You can use double curly braces ({{}}) to get values directly from the
Component class.
 Property binding: You can use this type of binding to set the property of an HTML element.
 Event binding: You can use this type of binding to handle user inputs.
 Attribute binding: This type of binding allows the setting of attributes to an HTML element.
 Class binding: You can use this type of binding to set CSS class names to the element.
 Style binding: You can use this type of binding to create inline CSS styles for the element.

S.YAMUNADEVI AP/IT 15
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

 Two-way binding with ngModel: You can use this type of binding with data entry forms to
receive and display data.
String Interpolation:
Interpolation involves using the {{}} double curly braces to evaluate a template expression. This can
be in a hard-coded form, or it can reference a property of the Component class.

Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
{{str1 + ' ' + name}}
<br>
<img src="{{imageSrc}}" />
<br>
<p>{{str2 + getLikes(likes)}}</p>`,
styles: [`
img{
width: 300px;
height: auto;
}
p{
font-size: 35px;
color: darkBlue;
} `]
})
export class AppComponent {
str1: string = "Hello my name is"
name: string = "Brendan"
str2: string = "I like to"
likes: string[] = ['hike', "rappel", "Jeep"]
getLikes = function(arr: any){
var arrString = arr.join(", ");
return " " + arrString
}
imageSrc: string = "../assets/images/angelsLanding.jpg"}

Output:

S.YAMUNADEVI AP/IT 16
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Property Binding
Property binding in Angular helps you set values for properties of HTML elements or directives. Use
property binding to do things such as toggle button features, set paths programmatically, and share
values between components.
Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<img [src]="myPic"/>
<br>
<button [disabled]="isEnabled">Click me</button><hr>
<button disabled="{!isEnabled}">Click me</button><br>
<p [ngClass]="className">This is cool stuff</p> `,
styles: [`
img {
height: 100px;
width auto;}
.myClass {
color: red;
font-size: 24px;
}
`]
})
export class AppComponent {
myPic: string = "../assets/images/sunset.JPG";
isEnabled: boolean = false;
className: string = "myClass";
}
Output:

Event Binding:
Event binding lets you listen for and respond to user actions such as keystrokes, mouse movements,
clicks, and touches.

S.YAMUNADEVI AP/IT 17
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Example:
Event Binding to Change the Image URL That Displays on the Web Page

import { Component } from '@angular/core';


@Component({
selector: 'app-root',
template: `
<div (mousemove)="move($event)">
<img [src]="imageUrl"
(mouseenter)="mouseGoesIn()"
(mouseleave)="mouseLeft()"
(dblclick)="changeImg()" /><br>
double click the picture to change it<br> The Mouse has {{mouse}}<hr>
<button (click)="changeImg()">Change Picture</button><hr>
<input (keyup)="onKeyup($event)"
(keydown)="onKeydown($event)"
(keypress)="keypress($event)"
(blur)="underTheScope($event)"
(focus)="underTheScope($event)">
{{view}}
<p>On key up: {{upValues}}</p>
<p>on key down: {{downValues}}</p>
<p>on key press: {{keypressValue}}</p>
<p (mousemove)="move($event)">x coordinates: {{x}}
<br> y coordinates: {{y}}
</p></div>`,
styles: [` img {
width: auto;
height: 300px;
}`] })
export class AppComponent {
counter = 0;
mouse: string;
upValues: string = '';
downValues: string = '';
keypressValue: string = "";
x: string = "";
y: string = '';
view: string = '';
46 mouseGoesIn = function(){
47 this.mouse = "entered";
};
mouseLeft = function(){ this.mouse = "left"; }
imageArray: string[] = ["../assets/images/flower.jpg","../assets/images/lake.jpg", //extensions are case
sensitiv"../assets/images/bison.jpg",
] imageUrl: string = this.imageArray[this.counter];

S.YAMUNADEVI AP/IT 18
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

changeImg = function(){
if(this.counter < this.imageArray.length - 1){
this.counter++;
}else{ this.counter = 0;
}
this.imageUrl=this.imageArray[this.counter]; }
onKeyup(event:any){
this.upValues = event.key;
this.upValues += event.target.value + ' | ';
}
onKeydown(event:any){
this.downValues = event.key;
this.downValues += event.target.value + " | ";
}
keypress(event:any){
this.keypressValue = event.key;
this.keypressValue += event.target.value + " | ";
}
move(event:any){
this.x = event.clientX;
this.y = event.clientY; }
underTheScope(event:any){
if(event.type == "focus"){
this.view = "the text box is focused";
}
else if(event.type == "blur"){
this.view = "the input box is blurred";
}
}
Console.log(event)
}};
Output:

S.YAMUNADEVI AP/IT 19
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Two-Way Binding
Two-way binding allows for data to be easily displayed and updated simultaneously. This makes it
easy to reflect any changes the user makes to the DOM. Angular does this by using ngModel to watch
for changes and then update the value.
syntax:
<input [(ngModel)] = "myValue">

Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<input [(ngModel)]="text"><br>
<input bindon-ngModel="text"><br>
<input [value]="text" (input)="text=$event.target.value">
<h1>{{text}}</h1>
`
})
export class AppComponent {
text: string = "some text here";
}
Class Binding

Class binding is used to bind CSS style tags to HTML elements. It assigns the class based on the
result of an expression being true or false. If the result is true, the class gets assigned.

Syntax:

<div [class.nameHere] = "true"></div>

<div [class.anotherName] = "false"></div>

Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div [class]="myCustomClass"></div>
<span [class.redText]="isTrue">Hello my blue friend</span> `,
styles: [`
.blueBox {
height: 150px;
width: 150px;
background-color: blue;
}
.redText{
color: red; font-size: 24px;
}`]
})

S.YAMUNADEVI AP/IT 20
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

export class AppComponent {


myCustomClass: string = 'blueBox';
isTrue = true;
}

BUILT-IN DIRECTIVES

 Directives are a combination of Angular template markup and supporting TypeScript code.
 Angular directive markups can be HTML attributes, element names, or CSS classes.
 The TypeScript directive code defines the template data and behavior of the HTML elements.
 The Angular compiler traverses the template DOM and compiles all directives.
 Then it links the directives by combining a directive with a scope to produce a new live view.
 The live view contains the DOM elements and functionality defined in the directive.

The following sections describe most of the Angular directives, which fall into three categories:
 Component: A directive with a template
 Structural: A directive that manipulates elements in the DOM
 Attribute: A directive that manipulates the appearance and behavior of a DOM element

Components Directives

Angular components are a form of structural directive that utilize a template. A component creates a
selector that is used as an HTML tag to dynamically add HTML, CSS, and Angular logic to the DOM.
Components are at the heart of Angular.

Structural Directives

Several directives dynamically update, create, and remove elements from the DOM. These directives
create the layout, look, and feel of an application.

Attribute Directives

Angular attribute directives modify how HTML elements look and behave. They are injected straight
into the HTML and dynamically modify how the user interacts with an HTML segment. Attribute
directives are so named because they often look like normal HTML attributes.

ngModel This directive watches a variable for changes and then updates
display values based on those changes. Consider these examples:
<input [(ngModel)]="text"><br>
<h1>{{text}}</h1>
ngForm This directive creates a form group and allows it to track the
values and validation within that form group. By using ngSubmit,
you can pass the form data as an object to the submission event.

ngStyle This directive updates the styles of an HTML element.

S.YAMUNADEVI AP/IT 21
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

App.Component.ts

01 import { Component } from '@angular/core';


@Component({
selector: 'app-root',
templateUrl: './attribute.component.html',
styleUrls: ['./attribute.component.css']
})
export class AppComponent {
colors: string[] = ["red", "blue", "green", "yellow"];
name: string;
11 color: string = 'color';
isDisabled: boolean = true;
classes:string[] = ['bold', 'italic', 'highlight'];
selectedClass:string[] = [];
enabler(){
this.isDisabled = !this.isDisabled;
}
addClass(event: any){
this.selectedClass = [];
var values = event.target.options;
var opt: any;
for (var i=0, iLen = values.length; i<iLen; i++){
opt = values[i];

if (opt.selected){
this.selectedClass.push(opt.text);
}
}
}
}

Attribute.component.html
<form>
<span>name: </span>
<input name="name" [(ngModel)]="name">
<br>
<span>color:</span>
<input type="checkbox" (click)="enabler()">
<select #optionColor [(ngModel)]="color" name="color"
[disabled]="isDisabled">
<option *ngFor="let color of colors" [value]="color">
{{color}}
</option>
</select><hr>
<span>Change Class</span><br>
<select #classOption multiple name="styles" (change)="addClass($event)">
<option *ngFor="let class of classes" [value]="class" >
{{class}}
</option>
</select><br>
<span>press and hold control/command
<br>to select multiple options

S.YAMUNADEVI AP/IT 22
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

</span>
</form>
<hr>
<span>Name: {{name}}</span><br>
<span [ngClass]="selectedClass"
[ngStyle]="{'color': optionColor.value}">
color: {{optionColor.value}}
</span><br>

Attribute.component.css
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
.highlight {
background-color: lightblue;
}

Output:

S.YAMUNADEVI AP/IT 23
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

UNIT V REACT

MERN STACK – Basic React applications – React Components – React State – Express RESTAPIs –
Modularization and Webpack – Routing with React Router – Server-side rendering

MERN STACK:

MERN Stack is a collection of powerful technologies and robust, used to develop scalable master web
applications comprising backend, front-end, and database components. It is JavaScript that is used
for the faster and easier development of full-stack web applications. MERN Stack is a technology that
is a user-friendly full-stack JavaScript framework for building applications and dynamic websites.

MERN Stack consists of four main components or can say four main technologies:

1. M stands for MongoDB ( Database ), mainly used for preparing document database and is a
NoSQL (Non-Structured Query Language ) Database System
2. E stands for Express, mainly used for developing Node.js web framework
3. R stands for React, mainly used for developing a client-side JavaScript framework
4. N stands for js, mainly used for developing the premier JavaScript web server

Each of these four technologies plays an important role in providing an end-to-end framework for the
developers. Even these four technologies play an important role in the development process of web
applications.

Reason to choose MERN Stack for building Mobile and Web applications:

1. Cost-effective:All the four technologies that are mentioned above, MERN (MongoDB,
Express.js, React.js, and Node.js) are used in MERN Stack is built on JavaScript that makes it
cost-effective and within less cost investment user will able to get the better results or output.
2. SEO friendly:Here, SEO (Search Engine Optimization) friendly means that Google, Yahoo
and other search engines can search each page on the website efficiently and easily, interpret
and correlate the content effectively with the searched text and easily index it in their database.
As whenever websites are created using MERN technologies, then it is always SEO friendly.
3. Better performance:Better performance refers to the faster response between backend and
front-end and database, which ultimately improves the website speed and yields better
performance, thus providing a smooth user experience.
4. Improves Security: It mainly concerns the security of applications generated using MERN;
her web application security refers to various processes, methods or technologies used for
protecting web servers and various web applications, such as APIs (Application user

S.YAMUNADEVI AP/IT 1
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

interface) from the attack by internet-based threats. Generally, secured hosting providers can
easily integrate applications created using the MERN stack. For more or better security Mongo
DB and Node.js security tools are also used.
5. Provide the fastest delivery:Any Web applications and mobile applications created by using
MERN Stack are built much faster, which also helps to provide faster delivery to our clients.
6. Provides faster Modifications: MERN stack technologies supports quick modifications as per
the client's request in the mobile and web applications.
7. Open Source: All the four technologies that are involved in MERN are open-source. This
feature allows developers to get solutions to queries that may evolve from the open portals
during development. As a result, it will be ultimately beneficial for a developer.
8. Easy to switch between client and server: MERN is very simple and fast because it is written
in only one language. And also, it is very easy to switch between client and server.

Architectural Structure of MERN Stack:

MERN has a 3-tier Architecture system mainly consisting of 3 layers -

These layers are as follows:

1. Web as front-end tier


2. Server as the middle tier
3. Database as backend tier

We already know that it comprises 4 components, i.e., MongoDB, Express.js, React, Node.js.

Now let us understand in more detail about these three tiers which are mentioned above -

i. Web or front-end tier - The top tier of the MERN stack is mainly handled by React.js. It is
one of the most prominent used open-source front-end JavaScript libraries used for building

S.YAMUNADEVI AP/IT 2
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Web applications. It is famous for creating dynamic client-side applications. React will help
you construct complex interfaces by using single components.
ii. It also connects those complex interfaces to data available on the backend server. React is used
to create mobile applications (React Native) and web applications. React allows the reusability
of code and can easily support it, which has many benefits and is much time saver. It permits
users to create large web applications that can easily change the data of the page even without
reloading the page.
iii. Server or middle-tier - It is just next level from the top layer and is mainly handled by two
components of the MERN stack, i.e., Express.js and Node.js. These two's components handle
it simultaneously because Express.js maintained the Server-side framework, running inside the
Node.js server. Express.js is one of the widely used backend development JavaScript
Frameworks. It allows developers to spin up robust APIs (Application Programming Interface)
and web servers much easier and simpler.
iv. It also adds helpful functionalities to Node.js HTTP (HyperText Transfer Protocol) objects.
Whereas on the other hand, Node.js plays a very important role in itself. It is an open-source
server environment, and it is a cross-platform runtime environment for executing JavaScript
code outside a browser. Node.js continuously uses JavaScript; thus, it's ultimately helpful for a
computer user to quickly create any net service or any net or mobile application.
v.

vi. Database as backend tier - It is one of the most important levels of the MERN Stack and is
mainly handled by MongoDB; the main role of a database is to store all the data related to your
application, for example - content, statistics, information, user profiles, comments and so on. It
mainly stores all the data for safety purposes. It maintains a proper record, which usually
returns the data to the user whenever required. It mainly stores the data in the database. It
generates two or more replica files of the data so that whenever the system fails, it can retrieve
the exact information or data that the user wanted earlier.
vii. It implies that MongoDB is not based on the table-like relational database structure. On the
other hand, it provides an altogether different mechanism for the retrieval and storage of
data. Mongo DB is the most popular NoSQL (NoSQL or Non Structured Query Language)
database, an open-source document-oriented database. The term 'NoSQL' typically means a
non-relational database that does not require a fixed schema or proper relational tables to store

S.YAMUNADEVI AP/IT 3
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

the necessary data in it. MongoDB stores the data in a different format other than the relational
tables, consisting of rows and columns.

Major Components of MERN Stack

Let us understand one by one about the four technologies or components that play a major role in
forming MERN Stack:

I. MongoDB

 Mongo DB is the most popular NoSQL (NoSQL or Non Structured Query Language) database,
an open-source document-oriented database.
 The term 'NoSQL' typically means a non-relational database that does not require a fixed
schema or proper relational tables to store the necessary data in it. MongoDB stores the data in
a different format other than the relational tables, consisting of rows and columns.
 It implies that MongoDB is not based on the table-like relational database structure. On the
other hand, it provides an altogether different mechanism for the retrieval and storage of data.
 The storage format in which the data is stored is known as BSON, which stands for Binary
JavaScript Object Notation; its binary structure encodes length and type of information, which
allows it to be parsed much more quickly.
 MongoDB uses BSON when storing documents in collections.
 It allows a highly scalable and flexible document structure.
 It is very faster as compared to RDBMS due to its efficient storage and indexing techniques.
 In MongoDB, complex join operations are not available; hence, it cannot support complex
transactions.
 MongoDB uses JavaScript for coding as a language which is one of the great advantages.
 It is Schemaless as any data stored which is stored in a separate document.
 In MongoDB, there is no concept of relationships or table formations, as this is happening in
RDBMS (Relational Database Management System), in which tables have a certain relation
between them.
 It also supports a flexible document model, which is very fast for any developer to create.
 MongoDB is one of the important types of NoSQL Databases. It is more scalable and provides
excellent performance if we notice that it will reach its scaling limit whenever a database runs
on a single server.
 MongoDB is a NoSQL database that scales by adding more and more servers and increases
productivity with its flexible document model.

Features of MongoDB -

❖ Schema-less Database: MongoDB has this one of the great features, which means that one
collection can hold different types of documents in it. Due to this extraordinary feature,
MongoDB provides great flexibility to databases. In the MongoDB database, a single collection
comprises multiple documents, and these documents may further comprise the different
numbers of values, fields, and so on. One document doesn't need to be a must to relate with the
other documents, as it happens in relational databases.
❖ Indexing: In the MongoDB database, one can easily fetch out the necessary data from the data
pool due to this indexing feature. In MongoDB, every data item has provided a particular

S.YAMUNADEVI AP/IT 4
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

index, categorized as primary and secondary indices. With this indexing, data retrieval is easier
for the user; it saves a lot of time. If the data is not indexed, the database searches each
document with the specified query, which takes lots of time and is inefficient.
❖ Document Oriented: In MongoDB, all the data has been stored in documents instead of tables
like SQL. Also, these documents have their unique object id. In these documents, the
informative data is stored in fields, i.e., key-value pairs instead of columns and rows, making
the data much more flexible and easier to fetch out rather than applying queries for every data
compared to RDBMS.
❖ Faster - MongoDB is very fast compared with relational database (RDBMS), which is
document-oriented. Each data item has its index value, making it easier for us to retrieve any
data without wasting time writing queries and making logic accordingly.
❖ Scalability: MongoDB is more scalable with the help of sharding. It provides horizontal
scalability. Here the term sharding means distributing data on multiple servers; in this, a large
amount of data has been divided into multiple small data chunks with the help of shard key.
These types of data chunks are evenly distributed across shards that reside across many
physical servers.
❖ High Performance: MongoDB has very high performance and has data persistency as
compared to other databases due to the presence of its great features like indexing, scalability,
replication, etc.
❖ Replication and Highly Available - MongoDB increases the availability of data due to
creating multiple copies of data on different servers. Providing redundancy or data replication
ultimately protects the database from any hardware failure and protects the data from being lost
in the future. I suppose if one server was not working or clashes due to error, and then data can
easily be retrieved from other active servers, who are currently working at that time, this will
all be due to redundancy of data.
❖ Aggregation: This feature of MongoDB is quite similar to the SQL GROUPBY clause. This
GROUPBY clause performs various operations on the grouped data to get the unique or
computed
❖ Simple Environment Setup - MongoDB has a very simple environment setup. One can easily
set up MongoDB in their system without applying much effort.

II. Express

❖ Express is a JavaScript server-side framework that runs within js.


❖ It is one of the best backend development JavaScript Frameworks.
❖ It provides the developer with a platform to create and maintain robust servers.
❖ Express is used for building and designing web and mobile applications easily and quickly.
❖ Express is used to provide server-side logic for mobile and web applications, and as such, it is
used all over the place.
❖ It allows developers to spin up robust APIs (Application Programming Interface) and web
servers much easier and simpler.
❖ Express makes robust web servers easier to organize your application's functionality with
routing and middleware.
❖ It also adds helpful functionalities to Node.js HTTP (HyperText Transfer Protocol) objects.
❖ It is an important component of the MERN and MEAN Stack and is used to build fast,
maintainable, and robust productions web applications.

S.YAMUNADEVI AP/IT 5
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Some important features of Express -

❖ Express makes Node.js web and mobile application development much easier and faster.
❖ Express has a very simple environment setup. One can easily set up Express in their system and
configure it without applying much effort.
❖ Express is very easy to connect with Databases like MongoDB.
❖ Based on HTTP methods and URLs, Express allows you to define the routes of your
application.
❖ Routing mainly aims to describe code that needs to be run in response to any request received
by a server. Routing is generally done based on the sequence of URL patterns and the HTTP
method, which is associated with the request.
❖ If you want to perform additional tasks and functions on any request and response, you can
easily use various middleware modules present in Express.
❖ The request is a message that arrives at the server for requesting something, and a Response is
a message sent by the server to a client in the form of the result of whatever the client asked
for.
❖ If any error occurs and you want to handle it, you can easily handle it by using error handling
middleware.
❖ Middleware is used somewhere during the lifecycle of request or response in the form of code.
It is mainly used to add functionalities or augment the behaviour of the webserver.
❖ Express also facilitates you to create a REST API (Representational State Transfer Application
Programming Interface)
❖ The REST APIs is also known as RESTful API, It mainly conforms to the constraints of REST
architectural style, and it also allows for interaction with RESTful web services. The main
advantage of REST API is that it provides great flexibility; it uses HTTP requests to access and
use data.
❖ The data flow into a website structure can easily facilitate by using the two template engines,
EJS and Jade, provided by Express.
❖ Express has a gigantic suite of third-party add-ons so that developers can use it to provide
better functionality, helps to increase the security level, and improve speed.
❖ It is very efficient and scalable; one can easily access it from anywhere and use it
simultaneously on different systems, and very fast.
❖ It is Single-threaded and Asynchronous.
❖ It also has the biggest community for Node.js.
❖ With its built-in router, it promotes code reusability.
❖ If we want to understand the architecture behind web servers and their working along with the
organization, then learning Express is the best option.

III. React

❖ React is one of the most popular open-source front-end JavaScript libraries used for building
Web applications.
❖ Before using react, it has some prerequisites that one should follow, that you must download
Node packages in your system with their latest versions. Also, you must have an understanding
of HTML, CSS and JavaScript.
❖ It is used to build user interfaces, especially for a single page web application.

S.YAMUNADEVI AP/IT 6
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

❖ It is not a JavaScript framework. It is just a JavaScript library developed by Facebook to solve


problems we could not solve earlier using other libraries while building web and mobile
applications.
❖ React is also used for making a grip over the view layer for mobile and web applications.
❖ It allows us to create reusable UI ( User Interface ) components.
❖ It was first created by software engineer Jordan Walke, who works for Facebook.
❖ React was first deployed in the Facebook news feed.
❖ It allows developers to create large web applications that can easily change the data of the page
even without reloading the page.
❖ The main objective of reacting is that it only works on user interfaces in the application,
whether mobile or web.
❖ It is very fast, simple and scalable.
❖ React is also used with a combination of other JavaScript libraries or frameworks.
❖ There are a lot of open-source platforms that are also used to make the front-end web and
mobile applications easier, like Angular js in MVC, but still, React replaces the Angular from
the MEAN stack. Now, most developers are using the MERN stack in which react is used; the
main reason is that it is very fast and has more advantages over other front-end frameworks.

Features of React

❖ Easy to learn - One of the great advantages of using react as it is very easier for a beginner to
learn it and make web and mobile applications using this front-end framework. Anyone with a
piece of previous basic knowledge in programming can easily understand React compared to
Angular. Angular is referred to as a ' Domain Specific Language ', so it is implied that it is
quite difficult to understand it. For Learning React, you need the basic knowledge of CSS and
HTML.
❖ Simple - React is one of the simplest open-source JavaScript front-end frameworks for
building web and mobile applications.
❖ It uses the component-based approach, uses plain and simple JavaScript, and a well-defined
lifecycle, which makes react much simpler and easier. So that one can easily learn it and build
professional mobile and web applications.
❖ It uses a simple syntax named JSX, which allows learners or developers to mix HTML with
JavaScript to make it easier for them to apply and use it for making efficient web and mobile
applications.
❖ Data Binding - React uses an application architecture known as Flux to control data flow to
components via one control point called the dispatcher. It uses one-way data binding, which is
easier to debug self-contained components of large React applications.
❖ Native Approach - React is used to create mobile applications (React Native) and web
applications. React allows the reusability of code and can easily support it, which has many
benefits and is much time saver. So simultaneously, at the same time, we can make IOS, Web
applications and Android.
❖ Performance - React has very fast performance due to the immutability of data. As the name
suggests, we can predict that the immutable data structures never change and allows you to
compare direct object references instead of doing deep-tree comparisons. The above reason
ultimately affects the performance of reacting and makes it faster.

S.YAMUNADEVI AP/IT 7
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

❖ Testability - React is very easy to test; whatever applications we are generating from the react,
whether mobile or web applications, it is much easier for us to test it on react.
❖ There are some state functions in the react, where various react views are treated as these
functions of the states, and we can easily manipulate with the state we pass to the react view.
Also, we can take a look at the output and triggered actions, functions, events, etc.

IV. Node.js

❖ Node.js is an open-source server environment, and it is a cross-platform runtime environment


for executing JavaScript code outside a browser.
❖ Node.js is not a programming language, and even it is not a framework.
❖ It is often used for building and developing numerous backend services like net applications,
mobile applications.
❖ Massive corporations principally utilize it in production like Uber, PayPal, Netflix,
❖ It may be a free ASCII text file platform and may be utilized by anybody.
❖ It will run on numerous operative systems like Windows, Mac, Linux, Unix, etc.
❖ It is incredibly simple to urge started with it and may even be used for agile development and
prototyping.
❖ It provides extremely ascendable and really quick services to the users.
❖ It is incredibly consistent and may be used as an ASCII text file cleaner.
❖ It continuously uses JavaScript; thus, it's ultimately helpful for a computer user to quickly
create any net service or any net or mobile application.
❖ It provides a massive system for any ASCII text file library.
❖ It contains a Non-blocking or, can say, Asynchronous nature.

Features of Node.JS:

❖ Easy Scalability: js is highly scalable because it uses a single-threaded model with event
looping. The server usually responds in a non-blocking way due to the help of the event
mechanism. It also makes the server very scalable instead of traditional servers that create
limited threads to handle requests. Node.js uses a single-threaded program, and this program
will be able to provide service to many requests.
❖ Fast: The event loop in Node.js handles all asynchronous operations, so Node.js acts like a fast
suite, and all the operations in Node.js are performed quickly like network connection, reading
or writing in the database, or file system. It runs on the V8 engine developed by Google.
❖ Easy to learn and debug code: js is quite easy to learn and debug because it uses JavaScript
for running code of web-based projects and various web and mobile applications. If you have
excelled in front-end developing and have a good command of JavaScript, you can easily build
and run the application on Node.js and explore more as much you can; it depends on your
capability.
❖ Real-time web apps: js plays a key role in making real-time web applications. And If you are
building a mobile or a web application, you can also use PHP, although it will take the same
time duration as when you use Node.js. Still, if someone wants to build gaming apps and chat
applications, then Node.js is a much better option because of its faster synchronization.

S.YAMUNADEVI AP/IT 8
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

❖ Caching Advantage: js provides the caching property in which a single module is cached.
Sometimes you do not need to re-execute the same lines of code because it has already been
cached using Node.js.
❖ Data Streaming:In Node.js, hypertext transfer protocol ( HTTP ) requests and responses area
unit thought-about as 2 separate events. They're knowledge streams, thus once you method a
file at the time of loading, it'll scale back the time and create it quicker once the info is given
within the style of transmissions. It additionally permits you to stream audio and video files at
lightning speed.
❖ Object-Oriented Approach: A huge complaint against Node.js was its JavaScript heritage,
which frequently involved many procedural spaghetti codes. Frameworks like Coffee Script
and Typescript solved these issues but came as a bolt-on for those who seriously cared about
coding standards. With the release and general adoption of ES6, Classes are built into the
framework, and the code looks syntactically similar to C#, Java and SWIFT.
❖ Event-Driven and Asyncronization- All Apis of the Node.js library area unit asynchronous,
that is, non-blocking. It suggests that a Node.js based mostly server ne'er waits for associate
API to come back knowledge. The server moves to the consequent API once line it, and a
notification mechanism of Events of Node.js helps the server to urge a response from the
previous API decision.
❖ Corporate Support: There are a lot of famous companies like PayPal, Wal-Mart, Microsoft,
Google that are using Node.js for building the applications. Node.js uses JavaScript, so most
companies are combining front-end and backend Teams into a single unit.

Advantages of MERN Stack

There are a lot of advantages of MERN Stack, some of them are mentioned below -

1. For a smooth development of any web application or mobile app, it supports MVC (Model
View Controller) architecture; the main purpose of this architecture is to separate the
presentation details with the business logic.
2. It covers all the web development stages starting from front-end development to backend
development with JavaScript.
3. It is an open-source framework mainly used to develop web-based or mobile applications and
is supported by the community.
4. It is very fast and efficient compared to MEAN Stack and mostly suitable for small
applications, whereas MEAN Stack is suitable for developing large applications.

REACT COMPONENTS:

❖ A Component is one of the core building blocks of React. In other words, we can say that every
application you will develop in React will be made up of pieces called components.
❖ Components make the task of building UIs much easier. Each component exists in the same
space, but they work independently from one another and merge all in a parent component,
which will be the final UI of your application.
❖ Every React component have their own structure, methods as well as APIs. They can be
reusable as per the needs of an application.

S.YAMUNADEVI AP/IT 9
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Types of Components:

❖ Functional Components
❖ Class Components

Functional Components

❖ In React, function components are a way to write components that only contain a render
method and don't have their own state.
❖ They are simply JavaScript functions that may or may not receive data as parameters.
❖ We can create a function that takes props(properties) as input and returns what should be
rendered.
❖ The functional component is also known as a stateless component because they do not hold or
manage state.

Syntax:

function WelcomeMessage(props) {

return <h1>Welcome to the , {props.name}</h1>;

Example: Functional component:

import React, { Component } from 'react';


class App extends React.Component {
render() {
return (
<div>
<First/>
<Second/>
</div>
);
}
}
class First extends React.Component {
render() {
return (
<div>
<h1>JavaTpoint</h1>
</div>
);
}
}
class Second extends React.Component {
render() {
return (
<div>
<h2>www.javatpoint.com</h2>
<p>This websites contains the great CS tutorial.</p>
</div>
);

S.YAMUNADEVI AP/IT 10
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

}
}
export default App;

Output:

Class Components:

❖ Class components are more complex than functional components.


❖ It requires to extend from React. Component and create a render function which returns a React
element. The data can pass from one class to other class components.
❖ You can create a class by defining a class that extends Component and has a render function.
❖ The class component is also known as a stateful component because they can hold or manage
local state.

Syntax:

class MyComponent extends React.Component {


render() {
return (
<div>This is main component.</div>
);
}
}

Example:Class component

import React, { Component } from 'react';


class App extends React.Component {
constructor() {
super();
this.state = {
data:
[
{
"name":"Abhishek"
},
{
"name":"Saharsh"
},
{
"name":"Ajay"
}

S.YAMUNADEVI AP/IT 11
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

]
}
}
render() {
return (
<div>
<StudentName/>
<ul>
{this.state.data.map((item) => <List data = {item} />)}
</ul>
</div>
);
}
}
class StudentName extends React.Component {
render() {
return (
<div>
<h1>Student Name Detail</h1>
</div>
);
}
}
class List extends React.Component {
render() {
return (
<ul>
<li>{this.props.data.name}</li>
</ul>
);
}
}
export default App;

Output:

REACT STATE:

❖ The state is an updatable structure that is used to contain data or information about the
component and can change over time.
❖ The change in state can happen as a response to user action or system event. It is the heart of
the react component which determines the behaviour of the component and how it will render.
❖ A state must be kept as simple as possible.
❖ It represents the component's local state or information.
❖ It can only be accessed or modified inside the component or by the component directly.

S.YAMUNADEVI AP/IT 12
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

The setState() Method

❖ State can be updated in response to event handlers, server responses, or prop changes. This is
done using the setState() method.
❖ The setState() method enqueues all of the updates made to the component state and instructs
React to re-render the component and its children with the updated state.
❖ Always use the setState() method to change the state object, since it will ensure that the
component knows it’s been updated and calls the render() method.

Props:
❖ Props are read-only components.
❖ It is an object which stores the value of attributes of a tag and work similar to the HTML
attributes.
❖ It allows passing data from one component to other components.
❖ It is similar to function arguments and can be passed to the component the same way as
arguments passed in a function.
❖ Props are immutable so we cannot modify the props from inside the component.

Example:
The following example is for React-State.When the on click event has triggered the state of the
component has changed according to the specification.

class Car extends React.Component {


constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
changeColor = () => {
this.setState({color: "blue"});
}
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
<button type="button"onClick={this.changeColor}>Change color</button>
</div>

S.YAMUNADEVI AP/IT 13
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

);
}
}

Output:

When the change color button has clicked this will returned to the following output:

Difference between Props and State:

S.NO PROPS STATES


1. Props are read-only. State changes can be asynchronous.

2. Props are immutable. State is mutable.

3. Props allow you to pass data from one State holds information about the
component to other components as an components.
argument.
4. Props can be accessed by the child State cannot be accessed by child
component. components.

5. Props are used to communicate between States can be used for rendering dynamic
components. changes with the component.

6. Stateless component can have Props. Stateless components cannot have State.

7. Props make components reusable. State cannot make components reusable.

8. Props are external and controlled by whatever The State is internal and controlled by
renders the component. the React Component itself.

S.YAMUNADEVI AP/IT 14
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

EXPRESS RESTAPI’S:

❖ Restful API is very popular and commonly used to create APIs for web-based applications.
❖ REST API is the standard way to send and receive data for web services.
❖ REST API is a software that allows two apps to communicate with one another over the
internet and through numerous devices.

GET
❖ used to request data from the server, but mainly this method is used to read data
PATCH
❖ used to update, change or replace the data
POST
❖ used to create new or to edit already existing data
Delete
❖ used to delete the data completely from the server

Step 1: First, open your editor. Now open your terminal and write a command npm init -y

S.YAMUNADEVI AP/IT 15
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Step 2: Now we will install express for that write command npm install express

Step 3: Now we will create a new file to write all our code index.js Write a few lines of code in the
first line and will import the express packages

Step 5: Then we will write a second argument as a callback to tell the API is working, now lets run this
code to check our API is working or node

Step 6: As our code is running fine, let's open our search engine and write localhost:4000, this will not
run,

Step 7: Now we need an add the second argument here localhost:4000/simplilearn

S.YAMUNADEVI AP/IT 16
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

MODULARIZATION IN WEBPACK:

Webpack is a JavaScript compiler that converts JS into modularized bundles in preparation for
production.

Webpack used to define entry points for frontend code as well as convert other files to readable
JavaScript and provide the bundle’s path as an output.
Two key elements to interact with the module system:
–require
–exports
Definition for Bundles:

Bundling is the process of following imported files and merging them into a single file: a “bundle”.

The example below is a basic implementation of a `config` object that defines an entry point at
`index.js` in the `src` folder of a web application.
module.exports = {
entry: {
main: './src/index.js'
},
...
}

When it comes to our config module’s `output`, despite an entry’s capability to hold multiple points of
entry, only one output path can be defined. The output property is used to define a destination path for
the newly created JavaScript bundle files as well as a file name. In other words, it defines how and
where to store our compiled code. We can implement this using the Node.js `path` module.

The example below imports the path module as well as store the created `bundle.js` file to the
`dist` folder:

const path = require('path')

module.exports = {
entry: {
main: './src/index.js'
},
output:
{
path: path.resolve(__dirname, 'dist'),

S.YAMUNADEVI AP/IT 17
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

fileName: 'dist/bundle.js'
}
}

Plugins in Webpack:

❖ When building our Webpack compiler we must also define any loaders and plugins that are
required.
❖ The loader property is used to convert any non-JavaScript files (TypeScript, JSON, CSS, etc.)
into readable, compiled JavaScript.
❖ A different loader is used per file type (i.e. `css-loader` is used for CSS files, style-loader can
handle SCSS, file-loader for handling JSON data, etc.).
❖ They are converted into modules that are added to a dependency graph generated by Webpack.
The example below shows a simple implementation of the loader property:

const path = require('path')

module.exports = {
input: {
main: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'dist/bundle.js'
},
module: {
rules: [
{
test: /\.css$/,
use: 'css-loader'
},
{
test: /\.txt$/,
use: 'raw-loader'
},
{
test: /\.ts$/,
use: 'ts-loader'
}
]
}
}

The module object in the example above defines the loaders to use to convert code into JavaScript
modules. These are executed from right to left, or rather, from the bottom to the top, with the last
loader expected to output a JavaScript code. As you can see, different file types require different
loaders. You can even use `module.rules` to chain multiple loaders to a single file-type if needed:

...
module: {
//loaders are executed from right to left/bottom to top
rules: [

S.YAMUNADEVI AP/IT 18
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
//configure loaders with the options property
{
loader: 'css-loader',
options: {
modules: true
}
},
//order of loader import: sass-loader, css-loader,
//style-loader
{
loader: 'sass-loader'
}
]
}
]
}
};

ROUTING WITH REACT ROUTER:

 Routing is a process in which a user is directed to different pages based on their action or
request. ReactJS Router is mainly used for developing Single Page Web Applications.
 React Router is used to define multiple routes in the application. When a user types a specific
URL into the browser, and if this URL path matches any 'route' inside the router file, the user
will be redirected to that particular route.
 React Router is a standard library system built on top of the React and used to create routing in
the React application using React Router Package.
 It provides the synchronous URL on the browser with data that will be displayed on the web
page.
 It maintains the standard structure and behaviour of the application and mainly used for
developing single page web applications.

Need of React Router

 React Router plays an important role to display multiple views in a single page application.
 Without React Router, it is not possible to display multiple views in React applications.
 Most of the social media websites like Facebook, Instagram uses React Router for rendering
multiple views.

React contains three different packages for routing. These are:

 react-router: It provides the core routing components and functions for the React Router
applications.
 react-router-native: It is used for mobile applications.
 react-router-dom: It is used for web applications design.

S.YAMUNADEVI AP/IT 19
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

It is not possible to install react-router directly in your application. To use react routing, first, you
need to install react-router-dom modules in your application. The below command is used to install
react router dom.

Components in React Router

There are two types of router components:

 <BrowserRouter>: It is used for handling the dynamic URL.


 <HashRouter>: It is used for handling the static request.

Example

About.js

import React from 'react'


class About extends React.Component {
render() {
return <h1>About</h1>
}
}
export default About
Contact.js

import React from 'react'


class Contact extends React.Component {
render() {
return <h1>Contact</h1>
}
}
export default Contact
App.js

import React from 'react'


class App extends React.Component {
render() {
return (
<div>
<h1>Home</h1>
</div>
)
}
}
export default App

Step-2: For Routing, open the index.js file and import all the three component files in it. Here, you
need to import line: import { Route, Link, BrowserRouter as Router } from 'react-router-dom' which
helps us to implement the Routing. Now, our index.js file looks like below.

S.YAMUNADEVI AP/IT 20
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Index.js

import React from 'react';


import ReactDOM from 'react-dom';
import { Route, Link, BrowserRouter as Router } from 'react-router-dom'
import './index.css';
import App from './App';
import About from './about'
import Contact from './contact'
const routing = (
<Router>
<div>
<h1>React Router Example</h1>
<Route path="/" component={App} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</div>
</Router>
)
ReactDOM.render(routing, document.getElementById('root'));
Step-3: Open command prompt, go to your project location, and then type npm start. You will get the
following screen.

React Router

Now, if you enter manually in the browser: localhost:3000/about, you will see About component is
rendered on the screen.

React Router

Step-4: In the above screen, you can see that Home component is still rendered. It is because the home
path is '/' and about path is '/about', so you can observe that slash is common in both paths which
render both components. To stop this behavior, you need to use the exact prop. It can be seen in the
below example.

Index.js

import React from 'react';


import ReactDOM from 'react-dom';
import { Route, Link, BrowserRouter as Router } from 'react-router-dom'
import './index.css';
import App from './App';
import About from './about'
import Contact from './contact'
const routing = (
<Router>
<div>
<h1>React Router Example</h1>
<Route exact path="/" component={App} />
<Route path="/about" component={About} />

S.YAMUNADEVI AP/IT 21
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

<Route path="/contact" component={Contact} />


</div>
</Router>
)
ReactDOM.render(routing, document.getElementById('root'));
Output:

SERVER SIDE RENDERING:

Server-side rendering (SSR) is a technique of rendering a client-side application on the server before
sending it to the client. This technique can be applied to React-based applications to improve
performance, SEO, and initial load time.

Server-side rendering (SSR) with React is the process of rendering a React-based application on the
server and sending the fully rendered HTML to the client. The client then "hydrates" the static HTML
with the React code to make the application dynamic and interactive.

This approach has several benefits, including improved performance (especially on slow networks),
improved SEO, and the ability to render the initial view of the application on the server, reducing the
time it takes to display the first view on the client. With SSR, the initial HTML and the CSS are
delivered to the client much faster, which provides a better user experience, especially on slower
devices and networks.

Uses of Server-Side Rendering:

There are several situations in which using Server Side Rendering React (SSR) can be beneficial:

S.YAMUNADEVI AP/IT 22
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Improved Performance

Server Side Rendering with React can improve the performance of your application, especially on
slower networks or devices, as the fully rendered HTML is sent to the client, resulting in faster initial
loading times.

 Server Side Rendering React eliminates the need for loaders or spinners during the initial
load. This suggests that, in general, Server Side Rendering will outperform Client Side
Rendering.
 Server Side Rendering React applications chunk JavaScript and CSS, optimize assets, and
render pages on the server before providing them to the client browser, leading to a quicker
initial load time.
 Faster load speeds result in a better user experience. This is one of the reasons why many
huge corporations are implementing Server Side Rendering React on their website.

Better SEO

 Server Side Rendering with React can improve the SEO of your application as search engines
can easily access and crawl the content of the page.
 Search engine crawlers may investigate the page with SSR to increase the SEO performance of
your app. This is due to the fact that all pages are rendered on the server with the appropriate
metadata, paragraphs, and headers before being sent to the client, allowing you to reap the
benefits of traditional website SEO.
 It's worth noting that, for the time being, Google and Bing can only index synchronous
JavaScript apps.
 The crawler will only take a few seconds for loading to complete if your app starts with a
loading spinner and then downloads content using Ajax.
 This implies that if you have asynchronously fetched material on pages where SEO is crucial,
SSR may be required.

Better Accessibility

 Server Side Rendering with React can improve the accessibility of your application for users
with slow or unreliable internet connections.

Dynamic Data

 Server Side Rendering with React can be useful when you want to generate dynamic content on
the server based on data from an API, database, or any other source.

Complex Applications

 Server Side Rendering with React can be beneficial for complex applications that require a lot
of data processing on the server.

Security

 Server Side Rendering with React can improve the security of your application by allowing you
to run sensitive code on the server, away from the client.

S.YAMUNADEVI AP/IT 23
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Working of Server Side Rendering

 Every page is originally rendered and loaded from the server when using Server Side
Rendering. Things are a little different now that Server Side (universal) React has been
introduced.
 The subsequent pages load straight from the client because the first page is rendered from the
server. The strength of the first server-side content combined with the quick subsequent loads,
which only request the content required for future requests, give you the best of both worlds.
 The most prevalent way of presenting information on the screen is Server Side Rendering. It
operates by transforming HTML files on the server into information that the browser can use.
 When you visit a website, your browser sends a request to the server that houses the website's
content.

The request normally takes only a few milliseconds, however, this is determined by a variety of
factors:

 Your internet connection speed.


 The server's location.
 How many people are attempting to view the site.
 And, the website's optimization.

When the request is completed, your browser returns the completely produced HTML and shows it on
the screen. If you then navigate to another page on the website, your browser will make another
request for the updated information. This will happen every time you visit a page for which your
browser does not have a cached version.

Example

Consider this HTML document, which has been put on a fictitious server with the HTTP
address sample.testwebsite.com.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample Website</title>
</head>
<body>
<h1>Our Sample Website</h1>
<p>Here is a sample of our new website</p>
<a href="http://sample.testwebsite.com/other.html.">Link</a>
</body>
</html>

Implementation of Server side rendering:

Step 1: Creating the React App and Modifying the App Component

npm install -g create-react-app

Then, create a new React application using the following command:

npx create-react-app my-app

S.YAMUNADEVI AP/IT 24
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

Go into the newly created app directory:

cd my-app

In this step, you will modify the existing App component to make it suitable for server-side rendering.
Here is the code for the modified App component:

import React from 'react';

class App extends React.Component {

render() {
return (
<div>
<h1>Hello World!</h1>
</div>
);
}
}

export default App;

Step 2: Creating an Express Server and Rendering the App Component

npm install express react-dom/server

import express from 'express';


import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from './src/App';
const app = express();
app.use(express.static('public'));
app.get('/', (req, res) => {
const html = ReactDOMServer.renderToString(<App />);
res.send(`
<html>
<head>
<title>Server-side Rendering with React</title>
</head>
<body>
<div id="root">${html}</div>
</body>
</html>
`);
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Step 3: Configuring Webpack, Babel, and NPM Scripts
"scripts": {
"build": "webpack --mode production",
"start": "node server.js",

S.YAMUNADEVI AP/IT 25
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT

"dev": "webpack-dev-server --mode development --open"


},

Let us now create a webpack.config.js file and add the following configuration:

const path = require("path");


module.exports = {
target: "node",
mode: "development",
entry: "./src/server/index.js",
output: {
path: path.resolve(__dirname, "build"),
filename: "server.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env", "@babel/preset-react"]
}
}
}
]
}
};

In your package.json file, add the following npm scripts:

"scripts": {
"build": "webpack --config webpack.config.js",
"start": "nodemon build/server.js"
},
With these steps, you have configured webpack and Babel to bundle and transpile your server code,
making it ready for execution.
To run the app, you can use the command npm start. The server will be running on port 3000 with all
these done. Now, open http://localhost:3000/ in your web browser and observe your server-side
rendered app.

S.YAMUNADEVI AP/IT 26

You might also like