Mean Stack Technologies Full Notes
Mean Stack Technologies Full Notes
SMTP. Html5 concepts, CSS3, Anatomy of a web page. XML: Document type Definition, XML schemas,
Document object model, XSLT, DOM and SAX Approaches
1. Internet :
The internet is a globally connected network system facilitating worldwide communication and access to data resources
through a huge collection of personal, public, business, academic and government networks. it’s gov erned by agencies
just like Internet Assigned Numbers Authority (or IANA) that establish universal protocols.
2. World Wide Web (WWW) :
World Wide Web (WWW), byname Web, is leading information retrieval service of web (the worldwide computer
network). Online gives users access to a huge array of documents that are connected to every other by means of
hypertext or hypermedia links—i.e., hyperlinks, electronic connections that link related pieces of data so as to permit a
user quick access to them. Hypertext allows the user to pick a word or phrase from text and thereby access other
documents that contain additional information concerning that word or phrase.
Page 1
1989.
An application layer protocol defines how the application processes running on different systems, pass the messages to each other.
DNS is a TCP/IP protocol used on different platforms. The domain name space is divided into three different sections: generic domains,
country domains, and inverse domain.
Generic Domains
Page 2
Label Description
Country Domain
The format of country domain is same as a generic domain, but it uses two-character country abbreviations (e.g., us for the United
States) in place of three character organizational abbreviations.
Inverse Domain
The inverse domain is used for mapping an address to a name. When the server has received a request from the client, and the server
contains the files of only authorized clients. To determine whether the client is on the authorized list or not, it sends a query to the DNS
server and ask for mapping an address to the name.
Page 3
Working of DNS
o DNS is a client/server network communication protocol. DNS clients send requests to the. server while DNS servers send responses
to the client.
o Client requests contain a name which is converted into an IP address known as a forward DNS lookups while requests containing
an IP address which is converted into a name known as reverse DNS lookups.
o DNS implements a distributed database to store the name of all the hosts available on the internet.
o If a client like a web browser sends a request containing a hostname, then a piece of software such as DNS resolver sends a
request to the DNS server to obtain the IP address of a hostname. If DNS server does not contain the IP address associated wi th a
hostname, then it forwards the request to another DNS server. If IP address has arrived at the resolver, which in turn completes the
request over the internet protocol.
HTTP:
Features of HTTP:
o Connectionless protocol: HTTP is a connectionless protocol. HTTP client initiates a request and waits for a response from the
server. When the server receives the request, the server processes the request and sends back the response to the HTTP client after
which the client disconnects the connection. The connection between client and server exist only during the current request and
response time only.
o Media independent: HTTP protocol is a media independent as data can be sent as long as both the client and server know how
to handle the data content. It is required for both the client and server to specify the content type in MIME-type header.
o Stateless: HTTP is a stateless protocol as both the client and server know each other only during the current request. Due to this
nature of the protocol, both the client and server do not retain the information between various requests of the web pages.
HTTP Transactions
Page 4
The above figure shows the HTTP transaction between client and server. The client initiates a transaction by sending a request message
to the server. The server replies to the request message by sending a response message
Messages
HTTP messages are of two types: request and response. Both the message types follow the same message format.
Request Message: The request message is sent by the client that consists of a request line, headers, and sometimes a body.
Response Message: The response message is sent by the server to the client that consists of a status line, headers, and sometimes a
body.
o A client that wants to access the document in an internet needs an address and to facilitate the access of documents, the HTTP
uses the concept of Uniform Resource Locator (URL).
o The Uniform Resource Locator (URL) is a standard way of specifying any kind of information on the internet.
o The URL defines four parts: method, host computer, port, and path
Page 5
o Method: The method is the protocol used to retrieve the document from a server. For example, HTTP.
o Host: The host is the computer where the information is stored, and the computer is given an alias name. Web pages are mainly
stored in the computers and the computers are given an alias name that begins with the characters "www". This field is not
mandatory.
o Port: The URL can also contain the port number of the server, but it's an optional field. If the port number is included, then it must
come between the host and path and it should be separated from the host by a colon.
o Path: Path is the pathname of the file where the information is stored. The path itself contain slashes that separate the directori es
from the subdirectories and files.
FTP
Objectives of FTP
Why FTP?
Although transferring files from one system to another is very simple and straightforward, but sometimes it can cause problems. For example,
two systems may have different file conventions. Two systems may have different ways to represent text and data. Two systems may have
different directory structures. FTP protocol overcomes these problems by establishing two connections between hosts. One connection is
used for data transfer, and another connection is used for the control connection.
Mechanism of FTP
The above figure shows the basic model of the FTP. The FTP client has three components: the user interface, control process, and data
transfer process. The server has two components: the server control process and the server data transfer process.
Page 6
o Control Connection: The control connection uses very simple rules for communication. Through control connection, we can
transfer a line of command or line of response at a time. The control connection is made between the control processes. The
control connection remains connected during the entire interactive FTP session.
o Data Connection: The Data Connection uses very complex rules as data types may vary. The data connection is made between
data transfer processes. The data connection opens when a command comes for transferring the files and closes when the file is
transferred.
FTP Clients
o FTP client is a program that implements a file transfer protocol which allows you to transfer files between two hosts on the
internet.
o It allows a user to connect to a remote host and upload or download the files.
o It has a set of commands that we can use to connect to a host, transfer the files between you and your host and close the
connection.
o The FTP program is also available as a built-in component in a Web browser. This GUI based FTP client makes the file transfer very
easy and also does not require to remember the FTP commands.
Advantages of FTP:
o Speed: One of the biggest advantages of FTP is speed. The FTP is one of the fastest way to transfer the files from one computer to
another computer.
o Efficient: It is more efficient as we do not need to complete all the operations to get the entire file.
o Security: To access the FTP server, we need to login with the username and password. Therefore, we can say that FTP is more
secure.
o Back & forth movement: FTP allows us to transfer the files back and forth. Suppose you are a manager of the company, you send
some information to all the employees, and they all send information back on the same server.
Disadvantages of FTP:
o The standard requirement of the industry is that all the FTP transmissions should be encrypted. However, not all the FTP prov iders
are equal and not all the providers offer encryption. So, we will have to look out for the FTP providers that provides encryption.
o FTP serves two operations, i.e., to send and receive large files on a network. However, the size limit of the file is 2GB that can be
sent. It also doesn't allow you to run simultaneous transfers to multiple receivers.
o Passwords and file contents are sent in clear text that allows unwanted eavesdropping. So, it is quite possible that attackers can
carry out the brute force attack by trying to guess the FTP password.
o It is not compatible with every system
SMTP
Page 7
Components of SMTP
o First, we will break the SMTP client and SMTP server into two components such as user agent (UA) and mail transfer agent (MTA ).
The user agent (UA) prepares the message, creates the envelope and then puts the message in the envelope. The mail transfer
agent (MTA) transfers this mail across the internet.
o SMTP allows a more complex system by adding a relaying system. Instead of just having one MTA at sending side and one at
receiving side, more MTAs can be added, acting either as a client or server to relay the email.
o The relaying system without TCP/IP protocol can also be used to send the emails
to users, and this is achieved by the use of the mail gateway. The mail gateway is
a relay MTA that can be used to receive an email.
Page 8
Working of SMTP
1. Composition of Mail: A user sends an e-mail by composing an electronic mail message using a Mail User Agent (MUA). Mail User
Agent is a program which is used to send and receive mail. The message contains two parts: body and header. The body is the
main part of the message while the header includes information such as the sender and recipient address. The header also
includes descriptive information such as the subject of the message. In this case, the message body is like a letter and header is
like an envelope that contains the recipient's address.
2. Submission of Mail: After composing an email, the mail client then submits the completed e-mail to the SMTP server by using
SMTP on TCP port 25.
3. Delivery of Mail: E-mail addresses contain two parts: username of the recipient and domain name. For
example, vivek@gmail.com, where "vivek" is the username of the recipient and "gmail.com" is the domain name.
If the domain name of the recipient's email address is different from the sender's domain name, then MSA will send the mail to the
Mail Transfer Agent (MTA). To relay the email, the MTA will find the target domain. It checks the MX record from Domain Name
System to obtain the target domain. The MX record contains the domain name and IP address of the recipient's domain. Once the
record is located, MTA connects to the exchange server to relay the message.
4. Receipt and Processing of Mail: Once the incoming message is received, the exchange server delivers it to the incoming server
(Mail Delivery Agent) which stores the e-mail where it waits for the user to retrieve it.
5. Access and Retrieval of Mail: The stored email in MDA can be retrieved by using MUA (Mail User Agent). MUA can be accessed
by using login and password.
Html5 concepts
HTML5 is the latest version of HTML, the markup language used to build structure or content on World Wide
Web. HTML5 is the latest web standard by W3C. Earlier HTML was used only to build webpage structure,
but HTML5 is a full on package to build websites, handle presentation, add functionalities and Web APIs.
HTML5 is the recommended version to build modern web applications as it is light and fastest version
of Hypertext Mark up Language, the code that describes web pages. HTML5 was formed in 2011.
Page 9
HTML5 Stack
Html5 is the combination of three web technologies:→
The term HTML5 means not only HTML, it is a combination of HTML, CSS and Javascript with APIs. For
example, drawing and animation using canvas, offline storage, microdata, audio and video, drag and
drop, geolocation, embedded fonts, web APIs etc. HTML5 includes new semantic tags and some old tags
Why HTML5
HTML5 has been designed to deliver almost everything you'd want to do on web without requiring additional
software such as browser plugins. It does everything from animation to apps, music to movies, and can also
be used to build complicated web applications that run in your browser.
HTML5 isn't proprietary, so you don't need to pay royalties to use it. It's also cross-platform, which means it
doesn't care whether you're using a tablet or a smart phone, a net-book, notebook, ultra-book or a Smart
TV if your browser supports HTML5, it should work flawlessly.
HTML Versions
Year Achievement
Page 10
Year Achievement
1995 HTML 2
1995 CSS
1995 JAVASCRIPT
1997 HTML 4
1998 CSS 2
2000 XHTML 1
2009 HTML5
2015 HTML5.1
2017 HTML5.2
Page 11
Edge 12 and above Browsers
HTML5 Doctype
HTML5 Doctype is short, and easy to remember. Unlike, HTML4 and XHTML, there is no DTD. As per W3C,
same doctype will be used in later versions of HTML.
<!DOCTYPE HTML> // New and shorter Doctype, no DTD Required
HTML5 Template
Default Template for HTML5 based websites.
<!doctype html>
<html lang="en"> //lang embedded in html
<head>
<title>HTML5 Page</title>
<meta charset="utf-8"> //Short charset meta tag
<link href="style.css" rel="stylesheet"> //No Type attribute
<script src="file.js"></script> //No Type attribute required
</head>
<body>
<h1>My First HTML5 page.</h1>
</body>
</html>
Section
Aside
Details
Summary
Time
BDI
Command
Figure
Figcaption
Picture
Footer
Header
Mark
Meter
Page 12
Nav
Progress
HTML5 Canvas
HTML5 SVG
Wbr
Article
An article defines a complete or an Self Contained composition in a webpage. An Article could be a Blog
post, forum, newspaper article, an independent content, user comment.
An article must have an heading or subheading, i.e h1-h6
<article>
<h2>Heading for Article</h2>
</article>
Section
An Section represents an generic section of a document. Section could be various sections of an article with
heading.
An section can include various chapters of a book or various webpage sections,
like introductions, content, contact info etc.
An section must have an heading. h2-h6
<article>
<h1>Article Heading</h1>
<section>
<h2>Subheading 1 for Section</h2>
</section>
<section>
<h2>Subheading 2 for Section</h2>
</section>
</article>
Aside
Aside is the sidebar of a container. The content inside aside is related to content next to it. Aside could be
sibling of div, section or article. But the content inside aside is relevant to adjacent sibling.
aside is use for links, sidebars, for ads and other content we want to put aside.
Aside Example
<aside>
<p>Aside</p>
</aside>
Details
Defines additional details that the user can view or hide. Content inside <details> is hidden. Only <summary> is
visible to user. User can click on summary to view details .
Page 13
Summary
Summary is the visible part of details. Except summary, everything details is hidden.
Details Example
Click to see details
<details>
<summary>Click To See</summary>
<p>Hello</p>
</details>
<details open>
<summary>Click To See</summary>
<p>Hello</p>
</details>
Time
Time tag is an inline level element, used to represents a time or exact date in Gregorian calender.
Page 14
<p> New Batch Timings are <time datetime="2017-12-08T10:00">10:00</time> AM.</p>
<p>Hello friend</p>
Command
Command Tag is an obsolete element of Html5. It represents a command, which a user can invoke.
<command>
<command type="command">
<command type="radio">
<command type="checkbox">
command tag is obsolete now. Even major browsers doesn't support command tag. Try avoid it.
Figure
Figure tag Specifies self-contained content, like images, illustrations, diagrams, code listings, etc. Figure can
have figcaption child to explain what figure is showing.
Figcaption
Figcaption is the caption of figure element.
<figure>
</figure>
Picture
HTML5 picture tag is used to show either high or low resolution image for Desktop, Mobile or particular device. We can
set two or more different images for different screens or resolutions, and browser will load a single resource from server,
Page 15
based on criteria. Like High quality images for Macbook and Full HD screens, medium quality images for normal screens
and small image for mobiles.
<picture>
</picture>
To test picture tag, minimize your browsers screen, or if using smartphone, use landscape and portrait mode to test.
<acronym>
<applet>
<basefont>
<big>
<center>
<dir>
<font>
<frame>
<frameset>
<marquee>
<noframes>
<strike>
<tt>
Page 16
HTML5 New Attributes
HTML5 introduced new attributes. All these attributes are functional and easy to use. HTML5 also removed so
many attributes as they are presentational, not functional.
html5-removed-attributes. Here is a list of html5 attributes.
Async
contenteditable
data
datetime
download
draggable
hidden
list
max
min
minlength
open
role
CSS3
CSS stands for Cascading Style Sheets. CSS is a standard style sheet language used for describing the presentation (i.e. the layout
and formatting) of the web pages.
Prior to CSS, nearly all of the presentational attributes of HTML documents were contained within the HTML markup (specifically
inside the HTML tags); all the font colors, background styles, element alignments, borders and sizes had to be explicitly described
within the HTML.
As a result, development of the large websites became a long and expensive process, since the style information were repeatedly
added to every single page of the website.
To solve this problem CSS was introduced in 1996 by the World Wide Web Consortium (W3C), which also maintains its standard. CSS
was designed to enable the separation of presentation and content. Now web designers can move the formatting information of the
web pages to a separate style sheet which results in considerably simpler HTML markup, and better maintainability.
CSS3 is the latest version of the CSS specification. CSS3 adds several new styling features and improvements to enhance the web
presentation capabilities.
Page 17
You can transform elements like scale, rotate, skew, etc. in 2D or 3D space.
You can create animations and transitions effects without using any JavaScript.
You can create print friendly version of your web pages.
The list does not end here, there are many other interesting things that you can do with CSS. You will learn about all of them in
detail in upcoming chapters.
CSS Save Lots of Time — CSS gives lots of flexibility to set the style properties of an element. You can write CSS once; and then the
same code can be applied to the groups of HTML elements, and can also be reused in multiple HTML pages.
Easy Maintenance — CSS provides an easy means to update the formatting of the documents, and to maintain the consistency
across multiple documents. Because the content of the entire set of web pages can be easily controlled using one or more style
sheets.
Pages Load Faster — CSS enables multiple pages to share the formatting information, which reduces complexity and repetition in
the structural contents of the documents. It significantly reduces the file transfer size, which results in a faster page loading.
Superior Styles to HTML — CSS has much wider presentation capabilities than HTML and provide much better control over the
layout of your web pages. So you can give far better look to your web pages in comparison to the HTML presentational elements
and attributes.
Multiple Device Compatibility — CSS also allows web pages to be optimized for more than one type of device or media. Using
CSS the same HTML document can be presented in different viewing styles for different rendering devices such as desktop, cell
phones, etc
Inline styles — Using the style attribute in the HTML start tag.
Embedded styles — Using the <style> element in the head section of a document.
External style sheets — Using the <link> element, pointing to an external CSS file.
In this tutorial we will cover all these three methods for inserting CSS one by one.
Inline Styles
Inline styles are used to apply the unique style rules to an element by putting the CSS rules directly into the start tag. It can be
attached to an element using the style attribute.
The style attribute includes a series of CSS property and value pairs. Each "property: value" pair is separated by a semicolon (;),
just as you would write into an embedded or external style sheets. But it needs to be all in one line i.e. no line break after the
semicolon, as shown here:
Example
<h1 style="color:red; font-size:30px;">This is a heading</h1>
<p style="color:green; font-size:22px;">This is a paragraph.</p>
<div style="color:blue; font-size:14px;">This is some text content.</div>
Using the inline styles are generally considered as a bad practice. As style rules are embedded directly inside the HTML tag, it causes
the presentation to become mixed with the content of the document; which makes the code hard to maintain and negates the
purpose of using CSS.
Page 18
Embedded or internal style sheets only affect the document they are embedded in.
Embedded style sheets are defined in the <head> section of an HTML document using the <style> element. You can define any
number of <style> elements in an HTML document but they must appear between the <head> and </head> tags. Let's take a look at
an example:
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>My HTML Document</title>
<style>
body { background-color: YellowGreen; }
p { color: #fff; }
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
</body>
</html>
An external style sheet holds all the style rules in a separate document that you can link from any HTML file on your site. External
style sheets are the most flexible because with an external style sheet, you can change the look of an entire website by changing just
one file.
You can attach external style sheets in two ways — linking and importing.
Example
body {
background: lightyellow;
font: 18px Arial, sans-serif;
}
h1 {
color: orange;
}
An external style sheet can be linked to an HTML document using the <link> tag. The <link> tag goes inside the <head> section, as
you can see in the following example:
<!DOCTYPE html>
<html lang="en">
</head>
</body> </html>
Page 19
What is Selector?
A CSS selector is a pattern to match the elements on a web page. The style rules associated with that selector will be applied to the
elements that match the selector pattern.
Selectors are one of the most important aspects of CSS as they allow you to target specific elements on your web page in vari ous
ways so that they can be styled.
Several types of selectors are available in CSS, let's take a closer look at them:
Universal Selector
The universal selector, denoted by an asterisk (*), matches every single element on the page.
The universal selector may be omitted if other conditions exist on the element. This selector is often used to remove the default
margins and paddings from the elements for quick testing purpose.
Let's try out the following example to understand how it basically works:
Example
Try this code »
* {
margin: 0;
padding: 0;
}
The style rules inside the * selector will be applied to every element in a document.
Note: It is recommended not to use the universal selector (*) too often in a production environment, since this selector matches
every element on a web page that puts too much of unnecessary pressure on the browsers. Use element type or class selector
instead.
Example
Try this code »
p {
color: blue;
}
The style rules inside the p selector will be applied on every <p> element (or paragraph) in the document and color it blue, regardless
of their position in the document tree.
Id Selectors
The id selector is used to define style rules for a single or unique element.
The id selector is defined with a hash sign (#) immediately followed by the id value.
Example
Try this code »
Page 20
#error {
color: red;
}
This style rule renders the text of an element in red, whose id attribute is set to error.
Note: The value of an id attribute must be unique within a given document — meaning no two elements in your HTML document
can share the same id value.
Class Selectors
The class selectors can be used to select any HTML element that has a class attribute. All the elements having that class will be
formatted according to the defined rule.
The class selector is defined with a period sign (.) immediately followed by the class value.
Example
Try this code »
.blue {
color: blue;
}
The above style rules renders the text in blue of every element in the document that has class attribute set to blue. You can make it
a bit more particular. For example:
Example
Try this code »
p.blue {
color: blue;
}
The style rule inside the selector p.blue renders the text in blue of only those <p> elements that has class attribute set to blue, and
has no effect on other paragraphs.
Descendant Selectors
You can use these selectors when you need to select an element that is the descendant of another element, for example, if you want
to target only those anchors that are contained within an unordered list, rather than targeting all anchor elements. Let's see how it
works:
Example
Try this code »
ul.menu li a {
text-decoration: none;
}
h1 em {
color: green;
}
The style rules inside the selector ul.menu li a applied to only those <a> elements that contained inside an <ul> element having
the class .menu, and has no effect on other links inside the document.
Similarly, the style rules inside the h1 em selector will be applied to only those <em> elements that contained inside the <h1> element
and has not effect on other <em> elements.
Page 21
Child Selectors
A child selector is used to select only those elements that are the direct children of some element.
A child selector is made up of two or more selectors separated by a greater than symbol ( >). You can use this selector, for instance,
to select the first level of list elements inside a nested list that has more than one level. Let's check out an example to understand
how it works:
Example
Try this code »
ul > li {
list-style: square;
}
ul > li ol {
list-style: none;
}
The style rule inside the selector ul > li applied to only those <li> elements that are direct children of the <ul> elements, and has
no effect on other list elements.
The selector h1 + p in the following example will select the <p> elements only if both the <h1> and <p> elements share the same
parent in the document tree and <h1> is immediately precedes the <p> element. That means only those paragraphs that come
immediately after each <h1> heading will have the associated style rules. Let's see how this selector actually works:
Example
Try this code »
h1 + p {
color: blue;
font-size: 18px;
}
ul.task + p {
color: #f0f;
text-indent: 30px;
}
The selector h1 ∼ p in the example below will select all the <p> elements that preceded by the <h1> element, where all the elements
share the same parent in the document tree.
Example
Try this code »
h1 ∼ p {
color: blue;
font-size: 18px;
}
ul.task ∼ p {
Page 22
color: #f0f;
text-indent: 30px;
}
There are more sophisticated selectors like attribute selectors, pseudo-classes, pseudo-elements. We will discuss about these
selectors in detail in the upcoming chapters.
Grouping Selectors
Often several selectors in a style sheet share the same style rules declarations. You can group them into a comma-separated list to
minimize the code in your style sheet. It also prevents you from repeating the same style rules over and over again. Let's take a look:
Example
Try this code »
h1 {
font-size: 36px;
font-weight: normal;
}
h2 {
font-size: 28px;
font-weight: normal;
}
h3 {
font-size: 22px;
font-weight: normal;
}
As you can see in the above example, the same style rule font-weight: normal; is shared by the selectors h1, h2 and h3, so it can
be grouped in a comma-separated list, like this:
Example
Try this code »
h1, h2, h3 {
font-weight: normal;
}
h1 {
font-size: 36px;
}
h2 {
font-size: 28px;
}
h3 {
font-size: 22px;
}
For instance, the color property specified in the body selector defines the default text color for the whole page. Let's try out the
following example to see how it works:
Example
Try this code »
body {
color: #ff5722;
}
Note: The color property normally inherits the color value from their parent element, except the case of anchor elements. For
example, if you specify color for the body element it will automatically be passed down to the headings, paragraphs, etc.
Page 23
Defining Color Values
Colors in CSS most often specified in the following formats:
CSS3 has introduced several other color formats such as HSL, HSLA and RGBA that also support alpha transparency. We'll learn
about them in greater detail in CSS3 color chapter.
For now, let's stick to the basic methods of defining the color values:
Color Keywords
CSS defines the few color keywords which lets you specify color values in an easy way.
These basic color keywords are: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and
yellow. The color names are case-insensitive.
Example
Try this code »
h1 {
color: red;
}
p {
color: purple;
}
Modern web browsers however practically support many more color names than what are defined in the CSS standard, but to be on
the safer side you should use hex color values instead.
See the reference on CSS color names, for a complete list of possible color names.
Hex represent colors using a six-digit code, preceded by a hash character, like #rrggbb, in which rr, gg, and bb represents the red,
green and blue component of the color respectively.
The value of each component can vary from 00 (no color) and FF (full color) in hexadecimal notation, or 0 and 255 in decimal
equivalent notation. Thus #ffffff represents white color and #000000 represents black color. Let's take a look the following
example:
Example
Try this code »
h1 {
color: #ffa500;
}
p {
color: #00ff00;
}
Note: Hexadecimal or Hex refers to a numbering scheme that uses 16 characters as its base. It uses the numbers 0 through 9 and
the letters A, B, C, D, E and F which corresponds to the decimal numbers 10, 11, 12, 13, 14 and 15 respectively.
Page 24
Tip: If hexadecimal code of a color has value pairs, it can also be written in shorthand notation to avoid extra typing, for example,
the hex color value #ffffff can be also be written as #fff, #000000 as #000, #00ff00 as #0f0, #ffcc00 as #fc0, and so on.
The rgb() function accepts three comma-separated values, which specify the amount of red, green, and blue component of the
color. These values are commonly specified as integers between 0 to 255, where 0 represent no color and 255 represent full or
maximum color.
The following example specifies the same color as in the previous example but in RGB notation.
Example
Try this code »
h1 {
color: rgb(255, 165, 0);
}
p {
color: rgb(0, 255, 0);
}
Note: You can also specify RGB values inside the rgb() function in percentage, where 100% represents full color, and 0% (not simply
0) represents no color. For example, you can specify the red color either as rgb(255, 0, 0) or rgb(100%, 0%, 0%) .
Tip: If R, G, and B are all set to 255, i.e. rgb(255, 255, 255) , the color would be white. Likewise, if all channels are set to 0,
i.e. rgb(0, 0, 0), the color would be black. Play with the RGB values in the following demonstration to understand how it actually
works.
Starting at the top of the web page, let's go through the anatomy of a web page:
Page Title
The page tile is set using the <title> </title> set of tags in the head section of the html coding. This is the only web page element within the head section
of the web page the visitor will see.
The URL is the domain name of the website. If the visitor just typed www.domainname.com they would be taken to the home page of the website.
File Name
File name is the web page file name. It cannot contain any spaces! The file name can be written as one long name (e.g. basichtmlarticles.htm), with
hyphens (e.g. basic-html-articles.htm, as shown in the image above) or with underscores (e.g. basic_html_articles.htm).
Page 25
When you create a web page you have to give it a name. The file name has what is called an extension at the end of it.
The extension at the end of the file name tells the browser what kind of file it is. A HTML document would have an extension of .htm or html. If your web
page uses a certain programming language it would have the appropriate extension. e.g. .php is for the PHP programming language, .asp is for the ASP
programming language.
Note: Servers and some browsers will not render (show) your page if you refer to it differently in your links than the way it is actually named. Basic-
Html-Articles.htm is different from basic-html-articles.htm to some servers and browsers. To combat this problem always name your files with lower case
letters. This way you don't have to remember how you capitalized a file name.
Scroll Bars
Scroll bars are on the right side and bottom of the browser window. If there is a scroll bar at the bottom (horizontal scroll bar) your web page content is
too wide for the browser window.
A web page layout should be designed so there is no horizontal scroll bar. You need to test your web page at different resolutions and on different
operating systems to see if the way the page is laid out will result in horizontal scroll bars when viewed at smaller resolut ions or by different operating
systems.
One way to avoid this problem is to use a flexible (fluid) design. A flexible design will adjust to the browser window size. As long as all your elements add
up to less than the browser width there will not be a horizontal scroll bar.
Next, we will look at the web page content portion of the anatomy of a web page.
Header
The header is at the very top of the web page. It usually contains a logo for the website.
Navigation
A website can use a left navigation system, a right navigation system or a navigation system that spans horizontally right under the header or above the
header.
The navigation system of a website has to be consistent throughout the website so the visitor will learn your navigation syst em. Changing the navigation
system from page to page is confusing to the visitor and they will get frustrated and leave!
Page 26
Web Page Content
Web page content includes everything between the <body> and </body> tags. We have already looked at some of the web page cont ent, the header
and navigation system. Also considered web page content is the web page footer (we will discuss this next) and the center section of this page that you
are looking at now.
Footer
This section is where you usually put your copyright notice, link to your privacy policy and your website contact information.
In this tutorial we have looked at the anatomy of a web page from top to bottom. We started with the page title, moved onto t he website URL and web
page file name, discussed vertical and horizontal scroll bars, then moved onto the web page content. The web page content portion of the anatomy of a
web page consists of everything between the <body> and </body> tags including the header, navigation, center web page content and the web page
footer.
What is a DTD?
DTD stands for Document Type Definition.
A DTD defines the structure and the legal elements and attributes of an XML document.
The DOCTYPE declaration above contains a reference to a DTD file. The content of the DTD file is shown and explained below.
XML DTD
Page 27
The purpose of a DTD is to define the structure and the legal elements and attributes of an XML document:
Note.dtd:
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
!DOCTYPE note - Defines that the root element of the document is note
!ELEMENT note - Defines that the note element must contain the elements: "to, from, heading, body"
!ELEMENT to - Defines the to element to be of type "#PCDATA"
!ELEMENT from - Defines the from element to be of type "#PCDATA"
!ELEMENT heading - Defines the heading element to be of type "#PCDATA"
!ELEMENT body - Defines the body element to be of type "#PCDATA"
Example
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note [
<!ENTITY nbsp " ">
<!ENTITY writer "Writer: Donald Duck.">
<!ENTITY copyright "Copyright: W3Schools.">
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>&writer; ©right;</footer>
</note>
With a DTD, you can verify that the data you receive from the outside world is valid.
Page 28
XML does not require a DTD.
When you are experimenting with XML, or when you are working with small XML files, creating DTDs may be a waste of time.
If you develop applications, wait until the specification is stable before you add a DTD. Otherwise, your software might stop working
because of validation errors.
XML schemas
An XML Schema describes the structure of an XML document, just like a DTD.
An XML document validated against an XML Schema is both "Well Formed" and "Valid".
XML Schema
XML Schema is an XML-based alternative to DTD:
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Page 29
XML Schemas support data types
XML Schemas support namespaces
With XML Schema, independent groups of people can agree on a standard for interchanging data.
When html document is loaded in the browser, it becomes a document object. It is the root element that represents the html document. It
has properties and methods. By the help of document object, we can add dynamic content to our web page.
Page 30
Methods of document object
Method Description
writeln("string") writes the given string on the doucment with newline character at the end.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name.
In this example, we are going to get the value of input text by user. Here, we are using document.form1.name.value to get the value of
name field.
Here, document is the root element that represents the html document.
value is the property, that returns the value of the input text.
Let's see the simple example of document object that prints name with welcome message.
1. <script type="text/javascript">
2. function printvalue(){
3. var name=document.form1.name.value;
Page 31
4. alert("Welcome: "+name);
5. }
6. </script>
7.
8. <form name="form1">
9. Enter Name:<input type="text" name="name"/>
10. <input type="button" onclick="printvalue()" value="print name"/>
11. </form>
XSLT
XSL (eXtensible Stylesheet Language) is a styling language for XML.
This tutorial will teach you how to use XSLT to transform XML documents into other formats (like transforming XML into HTML).
XSLT Example
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
XSLT References
Page 32
XSLT Elements
Description of all the XSLT elements from the W3C Recommendation, and information about browser support.
XSLT 2.0, XPath 2.0, and XQuery 1.0, share the same functions library. There are over 100 built-in functions. There are functions
for string values, numeric values, date and time comparison, node and QName manipulation, sequence manipulation, and more.
The World Wide Web Consortium (W3C) started to develop XSL because there was a need for an XML-based Stylesheet Language.
A <table> element could indicate an HTML table, a piece of furniture, or something else - and browsers do not know how to display
it!
Page 33
With the CSS3 Paged Media Module, W3C has delivered a new standard for document formatting. So, since 2013, CSS3 is
proposed as an XSL-FO replacement.
What is XSLT?
XSLT stands for XSL Transformations
XSLT is the most important part of XSL
XSLT transforms an XML document into another XML document
XSLT uses XPath to navigate in XML documents
XSLT is a W3C Recommendation
ADVERTISEMENT
XSLT is used to transform an XML document into another XML document, or another type of document that is recognized by a
browser, like HTML and XHTML. Normally XSLT does this by transforming each XML element into an (X)HTML element.
With XSLT you can add/remove elements and attributes to or from the output file. You can also rearrange and sort elements,
perform tests and make decisions about which elements to hide and display, and a lot more.
A common way to describe the transformation process is to say that XSLT transforms an XML source-tree into an XML result-
tree.
If you want to study XPath first, please read our XPath Tutorial.
Page 34
XSLT - Transformation
❮ PreviousNext ❯
Note: <xsl:stylesheet> and <xsl:transform> are completely synonymous and either can be used!
The correct way to declare an XSL style sheet according to the W3C XSLT Recommendation is:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
An XSL style sheet consists of one or more set of rules that are called templates.
The match attribute is used to associate a template with an XML element. The match attribute can also be used to define a
template for the entire XML document. The value of the match attribute is an XPath expression (i.e. match="/" defines the whol e
document).
Ok, let's look at a simplified version of the XSL file from the previous chapter:
Example
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
Page 35
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<tr>
<td>.</td>
<td>.</td>
</tr>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Example Explained
Since an XSL style sheet is an XML document, it always begins with the XML declaration: <?xml version="1.0" encoding="UTF-
8"?>.
The next element, <xsl:stylesheet>, defines that this document is an XSLT style sheet document (along with the version number
and XSLT namespace attributes).
The <xsl:template> element defines a template. The match="/" attribute associates the template with the root of the XML
source document.
The content inside the <xsl:template> element defines some HTML to write to the output.
The last two lines define the end of the template and the end of the style sheet.
The result from this example was a little disappointing, because no data was copied from the XML document to the output. In the
next chapter you will learn how to use the <xsl:value-of> element to select values from the XML elements.
Example
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<tr>
<td><xsl:value-of select="catalog/cd/title"/></td>
<td><xsl:value-of select="catalog/cd/artist"/></td>
</tr>
Page 36
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Example
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Example
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
Page 37
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<xsl:sort select="artist"/>
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Syntax
<xsl:if test="expression">
...some output if the expression is true...
</xsl:if>
Example
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
<th>Price</th>
</tr>
<xsl:for-each select="catalog/cd">
<xsl:if test="price > 10">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
<td><xsl:value-of select="price"/></td>
</tr>
Page 38
</xsl:if>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
DOM SAX
DOM stands for Document SAX stands for the Simple API
Object Model. for XML parsing.
DOM loads whole XML document SAX load a small part of XML
memory. memory.
It’s not suitable for a large XML It’s suitable for a large XML
file. file.
Page 39
files in java using DOM parser. files in java using SAX parser.
Page 40
UNIT II : JavaScript: The Basic of JavaScript: Objects, Primitives Operations and Expressions, Control
Statements, Arrays, Functions, Constructors, Pattern Matching using Regular Expressions. Angular Java
Script Angular JS Expressions: ARRAY, Objects, $eval, Strings, Angular JS Form Validation & Form
Submission, Single Page Application development using Angular JS.
What is JavaScript
JavaScript (js) is a light-weight object-oriented programming language which is used by several websites for scripting the webpages.
It is an interpreted, full-fledged programming language that enables dynamic interactivity on websites when applied to an HTML
document. It was introduced in the year 1995 for adding programs to the webpages in the Netscape Navigator browser. Since then,
it has been adopted by all other graphical web browsers. With JavaScript, users can build modern web applications to interact
directly without reloading the page every time. The traditional website uses js to provide several forms of interactivity and simplicity.
Although, JavaScript has no connectivity with Java programming language. The name was suggested and provided in the times
when Java was gaining popularity in the market. In addition to web browsers, databases such as CouchDB and MongoDB uses
JavaScript as their scripting and query language.
Features of JavaScript
1. All popular web browsers support JavaScript as they provide built-in execution environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a structured programming
language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
8. It provides good control to the users over the web browsers.
History of JavaScript
In 1993, Mosaic, the first popular web browser, came into existence. In the year 1994, Netscape was founded by Marc Andreessen.
He realized that the web needed to become more dynamic. Thus, a 'glue language' was believed to be provided to HTML to make
web designing easy for designers and part-time programmers. Consequently, in 1995, the company recruited Brendan
Eich intending to implement and embed Scheme programming language to the browser. But, before Brendan could start, the
company merged with Sun Microsystems for adding Java into its Navigator so that it could compete with Microsoft over the web
technologies and platforms. Now, two languages were there: Java and the scripting language. Further, Netscape decided to give a
similar name to the scripting language as Java's. It led to 'Javascript'. Finally, in May 1995, Marc Andreessen coined the first code of
Javascript named 'Mocha'. Later, the marketing team replaced the name with 'LiveScript'. But, due to trademark reasons and certain
other reasons, in December 1995, the language was finally renamed to 'JavaScript'. From then, JavaScript came into existence.
Page 41
Application of JavaScript
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and prompt dialog box),
o Displaying clocks etc.
JavaScript Example
1. <script>
2. document.write("Hello JavaScript by JavaScript");
3. </script>
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For example: car, pen, bike, chair, glass, keyboard,
monitor etc.
JavaScript is template based not class based. Here, we don't create class to get the object. But, we direct create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
object={property1:value1,property2:value2.....propertyN:valueN}
Page 42
Let’s see the simple example of creating object in JavaScript.
1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>
1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>
Here, you need to create function with arguments. Each argument value can be assigned in the current object by using this keyword.
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10. </script>
Page 43
Defining method in JavaScript Object
We can define method in JavaScript object. But before defining method, we need to add property in the function with same name as
method.
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6.
7. this.changeSalary=changeSalary;
8. function changeSalary(otherSalary){
9. this.salary=otherSalary;
10. }
11. }
12. e=new emp(103,"Sonoo Jaiswal",30000);
13. document.write(e.id+" "+e.name+" "+e.salary);
14. e.changeSalary(45000);
15. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
16. </script>
Page 44
7 Object.getOwnPropertyDescriptor() This method returns a property descriptor for the
specified property of the specified object.
JavaScript is a dynamic type language, means you don't need to specify type of the variable because it is dynamically used by
JavaScript engine. You need to use var here to specify the data type. It can hold any type of values such as numbers, strings etc. For
example:
Page 45
There are five types of primitive data types in JavaScript. They are as follows:
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For example:
1. var sum=10+20;
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
7. JavaScript Arithmetic Operators
8. Arithmetic operators are used to perform arithmetic operations on the operands. The following operators are known as
JavaScript arithmetic operators.
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
Page 46
/ Division 20/10 = 2
The JavaScript comparison operator compares the two operands. The comparison operators are as follows:
The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows:
Page 47
&& Logical AND (10==20 && 20==33) = false
= Assign 10+10 = 20
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-else.
Expressions
An expression is an unit of code that JavaScript interpreter can parse and compute to produce a value.
There are simple expressions like literal values and complex which are built from simpler ones usually using operators.
Primary expressions
Page 48
Primary expressions are the simplest expressions. There are three groups of primary expressions: literal values, variable references, and some
keywords.
Literal values
Literal values are constant values:
Variable references
Any identifier that appears in the code JavaScript interpreter assumes it is a variable and try to read its value.
this.name
this.displayName()
Other examples:
Function expression
Function expression defines a JavaScript function and the value of this expression is newly defined function. For example:
return x + y;
Page 49
}
Object initializer creates object with literal notation and the value of this expression is newly created object. It uses curly brackets surrounding
object properties separated by commas. For example:
var obj = {
prop1: "value1",
prop2: 2
};
Array initializer creates array with literal notation and the value of this expression is newly created array. It consists of square brackets
surrounding elements separated by commas. For example:
Object creation expression creates a new instance of object. It uses the keyword new followed by a constructor invocation.
An example:
There are two ways to access a property of an object: either using the object followed by a period and an identifier or using the object (or the
array) followed by square brackets with an identifier inside. It evaluates respectively to the value of an object property or an array element.
2 obj.x // 1
Page 50
3 obj['y'] // 2
5 arr[1] // 3
Invocation expression
1 func(arg);
2 obj.myMeth(x, y);
Parent object reference is a new added in ECMAScript 2015 expression using the keyword super. It evaluates to a parent object.
Spread operator
Spread operator named also rest operator allows an iterable to expand in place where multiple arguments (for function calls) or multiple elements
(for array literals) are expected.
Function call
function sum(a, b, c) {
return a + b + c;
Array literal
Page 51
var motorVehicles = ['car', 'motorcycle', 'truck'];
Other expressions
There are many other expressions, such as arithmetic, comparison, logical. These are covered in the chapter on operators.
Control Statements
1. Conditional Statements
Conditional statements in a program decide the next step based on the result. They
result in either True or False. The program moves to the next step if a condition is
Page 52
passed and true. However, if the condition is false, the program moves to another step.
IF
When you want to check for a specific condition with the IF condition, the inner code
Syntax:
if (condition) {
IF-ELSE
an extended version of IF. When you want to check a specific condition and two
Syntax:
if (condition)
else {
Page 53
As observed in an IF-ELSE statement, when the condition is satisfied, the first block of
code executes, and if the condition isn’t satisfied, the second block of code executes.
SWITCH
A switch statement is similar to IF and is useful when executing one code out of the
multiple code block execution possibilities based on the result of the expression passed.
Switch statements carry an expression, which is compared with values of the following
cases, and once a match is found, the code associated with that case executes.
Syntax:
switch (expression) {
case a:
Break;
case b:
Break;
case n:
Break;
default:
The above code contains an expression at the beginning, checked and compared with
the cases included. If the expression passed matches with case a, the code block inside
the case is executed. The same applies to cases b and n, and when the expression
Page 54
passed matches with none of the cases mentioned, it code enters the default case, and
Now that we have understood the conditional statements let’s learn about the second
2. Iterative Statement
Looping is a powerful tool for any programming language to execute instructions
repeatedly while the expression passed is satisfied. A basic example can be printing
“Hello World” 10 times. Writing the same print statement with “Hello world“ for 10
straight times will be time-consuming and impact the execution time. And this is where
looping comes in handy. There are three Iterative statements: WHILE, DO-WHILE,
WHILE
One of the control flow statements, the “while” statement, executes a code block when
the condition is satisfied. The difference between “IF” and “while” is that “IF” executes
code if the condition is satisfied, while “while” continues to repeat itself until the
condition is satisfied, unlike “IF”, which executes code only once if the condition is
Syntax:
Page 55
while (condition)
DO-WHILE
Similar to a while loop, with a twist that keeps a condition at the end of the loop. Also
known as Exit Control Loop, DO-WHILE executes the code and checks for the condition.
Syntax:
while
} (condition)
FOR
a for loop will execute a code block a number of times. Compared to other loops, FOR is
Syntax:
Page 56
With initialization, the loop starts by using a declared variable. Then, the condition part
checks the exit condition for the loop. When this condition returns true, the code block
inside is executed. If the condition returns false or fails, the control moves to the
increment/decrement part, where the variable is updated. The values are updated until
Arrays
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>
Output of the above example
Sonoo
Vimal
Ratan
Page 57
2) JavaScript Array directly (new keyword)
1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10. }
11. </script>
Test it Now
Arun
Varun
John
1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>
Test it Now
Page 58
Jai
Vijay
Smith
Let's see the list of JavaScript array methods with their description.
Methods Description
concat() It returns a new array object that contains two or more merged arrays.
copywithin() It copies the part of the given array with its own elements and returns the
modified array.
entries() It creates an iterator object and a loop that iterates over each key/value pair.
every() It determines whether all the elements of an array are satisfying the provided
function conditions.
flat() It creates a new array carrying sub-array elements concatenated recursively till
the specified depth.
flatMap() It maps all array elements via mapping function, then flattens the result into a
new array.
from() It creates a new array carrying the exact copy of another array element.
filter() It returns the new array containing the elements that pass the provided
function conditions.
find() It returns the value of the first element in the given array that satisfies the
specified condition.
findIndex() It returns the index value of the first element in the given array that satisfies
the specified condition.
forEach() It invokes the provided function once for each element of an array.
includes() It checks whether the given array contains the specified element.
indexOf() It searches the specified element in the given array and returns the index of the
first match.
keys() It creates an iterator object that contains only the keys of the array, then loops
through these keys.
lastIndexOf() It searches the specified element in the given array and returns the index of the
last match.
map() It calls the specified function for every array element and returns the new array
of() It creates a new array from a variable number of arguments, holding any type
of argument.
Page 59
pop() It removes and returns the last element of an array.
reduce(function, It executes a provided function for each value from left to right and reduces
initial) the array to a single value.
reduceRight() It executes a provided function for each value from right to left and reduces
the array to a single value.
some() It determines if any element of the array passes the test of the implemented
function.
slice() It returns a new array containing the copy of the part of the given array.
toString() It converts the elements of a specified array into string form, without affecting
the original array.
unshift() It adds one or more elements in the beginning of the given array.
values() It creates a new iterator object carrying values for each index in the array
Functions
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the code.
6.2M
1K
Page 60
1. function functionName([arg1, arg2, ...argN]){
2. //code to be executed
3. }
Let’s see the simple example of function in JavaScript that does not has arguments.
1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>
Test it Now
We can call function by passing arguments. Let’s see the example of function that has one argument.
1. <script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>
Test it Now
Click
We can call function that returns a value and use it in our program. Let’s see the example of function that returns value.
1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());
Page 61
8. </script>
Test it Now
In JavaScript, the purpose of Function constructor is to create a new Function object. It executes the code globally. However, if we
call the constructor directly, a function is created dynamically but in an unsecured way.
Syntax
Parameter
Method Description
apply() It is used to call a function contains this value and a single array of arguments.
call() It is used to call a function contains this value and an argument list.
Example 1
1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(2,5));
4. </script>
Output
Page 62
Example 2
1. <script>
2. var pow=new Function("num1","num2","return Math.pow(num1,num2)");
3. document.writeln(pow(2,3));
4. </script>
Test it Now
Output:
Constructors
Points to remember
1. <script>
2. class Employee {
3. constructor() {
4. this.id=101;
5. this.name = "Martin Roy";
6. }
7. }
8. var emp = new Employee();
9. document.writeln(emp.id+" "+emp.name);
10. </script>
Output:
11. 6.7M
12. 853
13. OOPs Concepts in Java
Page 63
The super keyword is used to call the parent class constructor. Let's see an example.
1. <script>
2. class CompanyName
3. {
4. constructor()
5. {
6. this.company="Javatpoint";
7. }
8. }
9. class Employee extends CompanyName {
10. constructor(id,name) {
11. super();
12. this.id=id;
13. this.name=name;
14. }
15. }
16. var emp = new Employee(1,"John");
17. document.writeln(emp.id+" "+emp.name+" "+emp.company);
18. </script>
Test it Now
Output:
1 John Javatpoint
The search pattern can be used for text search and text replace operations.
When you search for data in a text, you can use this search pattern to describe what you are searching for.
Regular expressions can be used to perform all types of text search and text replace operations.
Syntax
/pattern/modifiers;
Example
/w3schools/i;
Example explained:
Page 64
/w3schools/i is a regular expression.
The search() method uses an expression to search for a match, and returns the position of the match.
The replace() method returns a modified string where the pattern is replaced.
Example
Use a string to do a search for "W3schools" in a string:
Try it Yourself »
Page 65
Using String replace() With a String
The replace() method replaces a specified value with another value in a string:
Visit W3Schools!
Modifier Description
g Perform a global match (find all matches rather than stopping after the first match)
Page 66
Expression Description
Metacharacter Description
\d Find a digit
\b Find a match at the beginning of a word like this: \bWORD, or at the end of a
word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx Try it
»
Quantifier Description
Page 67
In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.
Using test()
The test() method is a RegExp expression method.
It searches a string for a pattern, and returns true or false, depending on the result.
Example
const pattern = /e/;
pattern.test("The best things in life are free!");
Since there is an "e" in the string, the output of the code above will be:
true
You don't have to put the regular expression in a variable first. The two lines above can be shortened to one:
Using exec()
The exec() method is a RegExp expression method.
It searches a string for a specified pattern, and returns the found text as an object.
Example
/e/.exec("The best things in life are free!");
Page 68
Syntax:
Angular.JS expressions are used to bind data to HTML the same way as the ng-bind directive. AngularJS
displays the data exactly at the place where the expression is placed.
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
<div ng-app="">
Addition : {{6+9}}
</div>
Page 69
</body>
</html>
Code Explanation:
1. The ng-app directive in our example is blank as shown in above screenshot. This only means that
there is no module to assign controllers, directives, services attached to the code.
2. We are adding a simple expression which looks at the addition of 2 numbers.
If the code is executed successfully, the following Output will be shown when you run your code in the
browser.
Output:
It can be seen that the addition of the two numbers 9 and 6 take place and the added value of 15
is displayed.
Angular.JS Numbers
Expressions can be used to work with numbers as well. Let’s look at an example of Angular.JS
expressions with numbers.
In this example, we just want to show a simple multiplication of 2 number variables called margin and
profit and displayed their multiplied value.
Page 70
Code Explanation:
1. The ng-init directive is used in angular.js to define variables and their corresponding values in the
view itself. It’s somewhat like defining local variables to code in any programming language. In
this case, we are defining 2 variables called margin and profit and assigning values to them.
2. We are then using the 2 local variables and multiplying their values.
If the code is executed successfully, the following Output will be shown when you run your code in the
browser.
Output:
Page 71
It can be clearly seen that the multiplication of the 2 numbers 2 and 200 take place, and the
multiplied value of 400 is displayed.
AngularJS Strings
Expressions can be used to work with strings as well. Let’s look at an example of Angular JS expressions
with strings.
In this example, we are going to define 2 strings of “firstName” and “lastName” and display them using
expressions accordingly.
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
First Name : {{firstName}}<br>
last Name : {{lastName}}
</div>
</body>
</html>
Code Explanation:
1. The ng-init directive is used define the variables firstName with the value “Guru” and the variable
lastName with the value of “99”.
2. We are then using expressions of {{firstName}} and {{lastName}} to access the value of these
variables and display them in the view accordingly.
If the code is executed successfully, the following Output will be shown when you run your code in the
browser.
Output:
Page 72
Angular.JS Objects
Expressions can be used to work with JavaScript objects as well.
Let’s look at an example of Angular.JS expressions with javascript objects. A javascript object consists of
a name-value pair.
Syntax:
In this example, we are going to define one object as a person object which will have 2 key value pairs of
“firstName” and “lastName”
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
First Name : {{person.firstName}}<br>
Last Name : {{person.lastName}}
</div>
</body>
</html>
Code Explanation:
1. The ng-init directive is used to define the object person which in turn has key value pairs of
firstName with the value “Guru” and the variable lastName with the value of “99”.
2. We are then using expressions of {{person.firstName}} and {{person.secondName}} to access the
value of these variables and display them in the view accordingly. Since the actual member
variables are part of the object person, they have to access it with the dot (.) notation to access
their actual value.
If the code is executed successfully, the following Output will be shown when you run your code in the
browser.
Page 73
Output:
AngularJS Arrays
Expressions can be used to work with arrays as well. Let’s look at an example of Angular JS expressions
with arrays.
In this example, we are going to define an array which is going to hold the marks of a student in 3
subjects. In the view, we will display the value of these marks accordingly.
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
Student Marks<br>
Subject1 : {{marks[0] }}<br>
Subject2 : {{marks[1] }}<br>
Subject3 : {{marks[2] }}<br>
</div>
</body>
</html>
Code Explanation:
1. The ng-init directive is used define the array with the name “marks” with 3 values of 1, 15 and 19.
2. We are then using expressions of marks [index] to access each element of the array.
If the code is executed successfully, the following Output will be shown when you run your code in the
browser.
Output:
Page 74
Difference between expression and $eval
The $eval function allows one to evaluate expressions from within the controller itself. So while
expressions are used for evaluation in the view, the $eval is used in the controller function.
In this example,
We are just going to use the $eval function to add 2 numbers and make it available in the scope object so
that it can be shown in the view.
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
$scope.value=$scope.$eval('a+b');
});
</script>
</body>
</html>
Code Explanation:
1. We are first defining 2 variables ‘a’ and ‘b’, each holding a value of 1.
2. We are using the $scope.$eval function to evaluate the addition of the 2 variables and assigning
it to the scope variable ‘value’.
3. We are then just displaying the value of the variable ‘value’ in the view.
Page 75
If the code is executed successfully, the following Output will be shown when you run your code in the
browser.
Output:
It also holds the information about whether the input fields have been touched, or modified, or not.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Angular JS Forms</title>
5. <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
6.
7. <style>
8. table, th , td {
9. border: 1px solid grey;
10. border-collapse: collapse;
11. padding: 5px;
12. }
13.
14. table tr:nth-child(odd) {
15. background-color: lightpink;
16. }
17.
18. table tr:nth-child(even) {
Page 76
19. background-color: lightyellow;
20. }
21. </style>
22.
23. </head>
24. <body>
25.
26. <h2>AngularJS Sample Application</h2>
27. <div ng-app = "mainApp" ng-controller = "studentController">
28.
29. <form name = "studentForm" novalidate>
30. <table border = "0">
31. <tr>
32. <td>Enter first name:</td>
33. <td><input name = "firstname" type = "text" ng-model = "firstName" required>
34. <span style = "color:red" ng-show = "studentForm.firstname.$dirty && studentForm.firstname.$invalid">
35. <span ng-show = "studentForm.firstname.$error.required">First Name is required.</span>
36. </span>
37. </td>
38. </tr>
39.
40. <tr>
41. <td>Enter last name: </td>
42. <td><input name = "lastname" type = "text" ng-model = "lastName" required>
43. <span style = "color:red" ng-show = "studentForm.lastname.$dirty && studentForm.lastname.$invalid">
44. <span ng-show = "studentForm.lastname.$error.required">Last Name is required.</span>
45. </span>
46. </td>
47. </tr>
48.
49. <tr>
50. <td>Email: </td><td><input name = "email" type = "email" ng-model = "email" length = "100" required>
51. <span style = "color:red" ng-show = "studentForm.email.$dirty && studentForm.email.$invalid">
52. <span ng-show = "studentForm.email.$error.required">Email is required.</span>
53. <span ng-show = "studentForm.email.$error.email">Invalid email address.</span>
54. </span>
55. </td>
56. </tr>
57. <tr>
58. <td>
59. <button ng-click = "reset()">Reset</button>
60. </td>
61. <td>
62. <button ng-disabled = "studentForm.firstname.$dirty &&
63. studentForm.firstname.$invalid || studentForm.lastname.$dirty &&
64. studentForm.lastname.$invalid || studentForm.email.$dirty &&
65. studentForm.email.$invalid" ng-click="submit()">Submit</button>
66. </td>
67. </tr>
68. </table>
69. </form>
Page 77
70. </div>
71. <script>
72. var mainApp = angular.module("mainApp", []);
73. mainApp.controller('studentController', function($scope) {
74. $scope.reset = function(){
75. $scope.firstName = "Sonoo";
76. $scope.lastName = "Jaiswal";
77. $scope.email = "sonoojaiswal@javatpoint.com";
78. }
79. $scope.reset();
80. });
81. </script>
82. </body>
83. </html>
Angular follows MVC architecture, so every angular app consists of different modules.
app.controller('FirstController', function($scope) {
});
The module created in the first step and the controller performed in the second step specify both in the ng-controller
attribute.
<!doctype html>
<html ng-app="myApp">
<head>
Page 78
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
</head>
<body ng-controller="FirstController">
<h1>{{message}}</h1>
<script src="app.js"></script>
</body>
</html>
<!doctype html>
<html ng-app="myApp">
<head>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>
</head>
<body>
<div ng-view></div>
<script src="app.js"></script>
</body>
</html>
A templateUrl and a controller must be specified for each route. In cases where a user attempts to navigate to an unexistent
route, an exception must be handled. Then, the user can be redirected to the “/” route using an “otherwise” function.
app.config(function($routeProvider) {
Page 79
$routeProvider
.when('/', {
templateUrl : 'pages/first.html',
controller : 'FirstController'
})
.when('/blog', {
templateUrl : 'pages/second.html',
controller : 'SecondController'
})
.when('/about', {
templateUrl : 'pages/third.html',
controller : 'ThirdController'
})
.otherwise({redirectTo: '/'});
});
app.controller('FirstController', function($scope) {
});
app.controller('SecondController', function($scope) {
});
Page 80
app.controller('ThirdController', function($scope) {
});
first.html
<h1>First</h1>
<h3>{{message}}</h3>
second.html
<h1>Second</h1>
<h3>{{message}}</h3>
third.html
<h1>Third</h1>
<h3>{{message}}</h3>
<!doctype html>
<html ng-app="myApp">
<head>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>
</head>
<body>
<a href="#/">First</a>
<a href="#/second">Second</a>
<a href="#/third">Third</a>
Page 81
<div ng-view></div>
<script src="app.js"></script>
</body>
</html>
Step 9: Include the HTML of the Above Pages to Index.html file with Script Tag
<!doctype html>
<html ng-app="myApp">
<head>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>
</head>
<body>
<h1>First</h1>
<h3>{{message}}</h3>
</script>
<h1>Second</h1>
<h3>{{message}}</h3>
</script>
<h1>Third</h1>
<h3>{{message}}</h3>
</script>
Page 82
<a href="#/">First</a>
<a href="#/second">Second</a>
<a href="#/third">Third</a>
<div ng-view></div>
<script src="app.js"></script>
</body>
</html>
That’s it! After successfully performing the above steps, you can easily create single-page applications using Angular and
also simplify many other complex tasks of your projects.
Page 83
Angular JS & Node.JS – Unit-2 Web Technologies
Node.js Introduction
Why Node.js?
Node.js eliminates the waiting, and simply continues with the next request.
Node.js runs single-threaded, non-blocking, asynchronous programming, which is very memory efficient.
Advantages of Node.js
NodeJs can be learned quickly by those who are already well-versed with JavaScript. With NodeJs,
developers can use the same coding language for both front-end and back-end development. Therefore,
JavaScript is the most preferred language for full-stack development.
Thus, it offers convenience to programmers as they don’t need to switch between multiple coding
languages and they also need to deal with fewer files.
3. V8 Engine
Originally developed for Chrome, V8 Engine has now been adapted to suit web app development
purposes. The V8 Engine is one of the most superior engines that can translate JavaScript to general
machine coding language with the help of C++. Thus, the V8 Engine is ultimately helpful for servers and
all machine language-based products.
NodeJS is a lightweight tool that aids in the faster development and deployment of applications.
It also assists in the development of microservices. This is because NodeJs is capable of fast data
processing and provides non-locking algorithms which are extremely beneficial for the development of
microservices.
Additionally, NodeJs can also handle concurrent requests simultaneously. This is ultimately crucial for
microservices as they need to constantly and quickly communicate with each other.
5. Scalable
Most businesses nowadays prefer scalable software.
First of all, NodeJs takes care of concurrent requests. The second reason that makes NodeJs popular is
that it has a cluster module that handles load balance for all running CPU cores.
The third and most interesting feature of NodeJs is its ability to split software horizontally. It
accomplishes this with the help of child processes. This means that businesses can present different app
versions to different target audiences which helps them address the personalization preferences of
customers.
Next, NodeJs employs an event-based software development approach in which there is no defined
output order and the output is delivered solely based upon the user’s inputs.
Being an open-source solution, NodeJs offers an extensive global community. The advantage of having a
larger community is that developers can seek help from community members to get responses for their
queries instantly. Community members share tools, modules, packages, and frameworks among each
other completely free of cost.
The official package ecosystem of NodeJs is the node package manager (NPM) with a dynamic
repository of multiple tools and modules which are used by developers for app development. NPM is like
a free marketplace for developers.
NPM can help in file upload management, download updates, and establish connectivity to MySQL
databases.
NodeJs reduces the number of servers needed to host the application and ultimately cuts down the page
load time by 50%.
When data travels as different streams, processing them consumes a lot of time. So, NodeJS saves the
time that goes into processing data by processing a file simultaneously while it is being uploaded.
In the traditional web server model, each request is handled by a dedicated thread from the thread
pool. If no thread is available in the thread pool at any point of time then the request waits till the next
available thread. Dedicated thread executes a particular request and does not return to thread pool
until it completes the execution and returns a response.
Node.js processes user requests differently when compared to a traditional web server model. Node.js
runs in a single process and the application code runs in a single thread and thereby needs less
resources than other platforms. All the user requests to your web application will be handled by a
single thread and all the I/O work or long running job is performed asynchronously for a particular
request. So, this single thread doesn't have to wait for the request to complete and is free to handle the
next request. When asynchronous I/O work completes then it processes the request further and sends
the response.
An event loop is constantly watching for the events to be raised for an asynchronous job and
executing callback function when the job completes. Internally, Node.js uses libev for the event loop
which in turn uses internal C++ thread pool to provide asynchronous I/O.
The following figure illustrates asynchronous web server model using Node.js.
Node.js process model increases the performance and scalability with a few caveats. Node.js is not fit
for an application which performs CPU-intensive operations like image processing or other heavy
computation work because it takes time to process a request and thereby blocks the single thread.
Node.js Modules
Built-in Modules
Node.js has a set of built-in modules which you can use without any further installation.
Include Modules
To include a module, use the require() function with the name of the module:
Now your application has access to the HTTP module, and is able to create a server:
You can create your own modules, and easily include them in your applications.
The following example creates a module that returns a date and time object:
Example
exports.myDateTime = function () {
return Date();
};
Use the exports keyword to make properties and methods available outside the module file.
Now you can include and use the module in any of your Node.js files.
Example
Notice that we use ./ to locate the module, that means that the module is located in the same folder as the
Node.js file.
Save the code above in a file called "demo_module.js", and initiate the file:
Initiate demo_module.js:
If you have followed the same steps on your computer, you will see the same result as the
example: http://localhost:8080
The Node.js file system module allows you to work with the file system on your computer.
var fs = require('fs');
Read files
Create files
Update files
Delete files
Rename files
Read Files
Assume we have the following HTML file (located in the same folder as Node.js):
demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
Create a Node.js file that reads the HTML file, and return the content:
Example
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
Save the code above in a file called "demo_readfile.js", and initiate the file:
Initiate demo_readfile.js:
If you have followed the same steps on your computer, you will see the same result as the
example: http://localhost:8080
Create Files
The File System module has methods for creating new files:
fs.appendFile()
fs.open()
fs.writeFile()
The fs.appendFile() method appends specified content to a file. If the file does not exist, the file will be
created:
Example
var fs = require('fs');
The fs.open() method takes a "flag" as the second argument, if the flag is "w" for "writing", the specified
file is opened for writing. If the file does not exist, an empty file is created:
Example
var fs = require('fs');
The fs.writeFile() method replaces the specified file and content if it exists. If the file does not exist, a
new file, containing the specified content, will be created:
Example
var fs = require('fs');
Update Files
fs.appendFile()
fs.writeFile()
The fs.appendFile() method appends the specified content at the end of the specified file:
Example
var fs = require('fs');
Example
var fs = require('fs');
Delete Files
To delete a file with the File System module, use the fs.unlink() method.
Example
Delete "mynewfile2.txt":
var fs = require('fs');
Rename Files
To rename a file with the File System module, use the fs.rename() method.
Example
Rename "mynewfile1.txt" to "myrenamedfile.txt":
var fs = require('fs');
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
if (err) throw err;
console.log('File Renamed!');
});
Upload Files
Parse an address with the url.parse() method, and it will return a URL object with each part of the address
as properties:
Example
Now we know how to parse the query string, and in the previous chapter we learned how to make
Node.js behave as a file server. Let us combine the two, and serve the file requested by the client.
Create two html files and save them in the same folder as your node.js files.
summer.html
<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
</body>
</html>
winter.html
<!DOCTYPE html>
<html>
<body>
<h1>Winter</h1>
<p>I love the snow!</p>
</body>
</html>
Create a Node.js file that opens the requested file and returns the content to the client. If anything goes
wrong, throw a 404 error:
demo_fileserver.js:
Initiate demo_fileserver.js:
If you have followed the same steps on your computer, you should see two different results when
opening these two addresses:
http://localhost:8080/summer.html
Summer
http://localhost:8080/winter.html
Winter
Node.js Events
Events in Node.js
Every action on a computer is an event. Like when a connection is made or a file is opened.
Objects in Node.js can fire events, like the readStream object fires events when opening and closing a
file:
Example
var fs = require('fs');
var rs = fs.createReadStream('./demofile.txt');
rs.on('open', function () {
console.log('The file is open');
});
Events Module
Node.js has a built-in module, called "Events", where you can create-, fire-, and listen for- your own
events.
To include the built-in Events module use the require() method. In addition, all event properties and
methods are an instance of an EventEmitter object. To be able to access these properties and methods,
create an EventEmitter object:
You can assign event handlers to your own events with the EventEmitter object.
In the example below we have created a function that will be executed when a "scream" event is fired.
Example
var events = require('events');
var eventEmitter = new events.EventEmitter();
It's important to refer to the documentation and resources provided by the specific
cloud platform you choose, as the deployment process may vary depending on the
platform and services you utilize.
UNIT-IV
Here are some key concepts and principles associated with RESTful web services:
Page 97
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
By following these principles, RESTful web services provide a scalable and flexible
architecture for building distributed systems. They are widely used for developing
web APIs, enabling different client applications (web, mobile, IoT, etc.) to interact
with server resources over the internet in a standardized manner.
RESTful web services adhere to the principles of the uniform interface, which
provides a consistent and standardized way for clients to interact with server
resources. The uniform interface in REST is based on the following key elements:
Page 98
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
By following the principles of the uniform interface, RESTful web services provide a
standardized and interoperable approach for clients to interact with server resources.
Page 99
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
The uniformity of the interface simplifies client implementation and enables loose
coupling between the client and server, promoting scalability and flexibility in
distributed systems.
Designing URIs:
When designing URLs for RESTful web services, it's important to follow best
practices and adhere to the principles of REST. Here are some guidelines to consider:
Page 100
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
7. Use Query Parameters for Filtering, Sorting, and Pagination: Use query
parameters to handle filtering, sorting, and pagination requirements. For example,
/users?role=admin&sort=name to retrieve users filtered by role and sorted by name.
8. Avoid Including Actions in URLs: Instead of including actions (verbs) in
URLs, use appropriate HTTP methods to perform actions on resources. For example,
use POST to create a new resource, PUT to update a resource, and DELETE to
delete a resource.
9. Versioning: If you anticipate making changes to your API in the future,
consider incorporating versioning into the URL structure. For example, /v1/users to
represent the first version of the users resource.
10. Follow Security Considerations: Ensure URLs don't expose sensitive
information and implement proper security measures, such as authentication and
authorization, to protect your API.
Remember, designing URLs for RESTful web services should focus on creating a
clear, intuitive, and consistent structure that represents resources and promotes ease of
use for clients interacting with your API.
Weblinking:
Here are some key points to understand about web linking in RESTful web services:
Page 101
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
“rel”: “relation-type” ,
“href” : “https://example.com/resourse “,
“title” : “Link-Title”
Page 102
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
By incorporating web linking into RESTful web services, APIs become more self-
descriptive, discoverable, and adaptable. Clients can navigate the API dynamically by
following the provided links, reducing coupling and promoting a more flexible client-
server interaction.
Conditional Requests :
Conditional requests are a feature in RESTful web services that allow clients to
perform requests with certain conditions, enabling more efficient and optimized
interactions with the server. Conditional requests are based on HTTP headers and
status codes to indicate the conditions and responses to those conditions. Here are the
key components of conditional requests in RESTful web services:
Page 103
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
ReactJS:
Page 104
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
5. React Native: React Native, a framework built on top of React, enables the
development of native mobile applications for iOS and Android platforms using
JavaScript. With React Native, developers can write a single codebase that runs on
multiple platforms, providing a significant advantage for cross-platform app
development.
React has gained popularity due to its simplicity, performance optimizations, and a
large ecosystem of community-driven libraries and tools. It is widely used by both
small and large organizations to build interactive and dynamic web applications.
Additionally, React's component-based architecture and declarative nature make it
easier to test, maintain, and collaborate on projects.
While React JS is a popular and powerful framework for building web applications,
developers may encounter certain obstacles or roadblocks during their journey. Here
are a few common challenges and ways to overcome them:
1. Learning Curve: React has a learning curve, especially for developers who are
new to JavaScript frameworks or have a background in different frameworks. It may
take time to grasp concepts like JSX, component lifecycle, state management, and
React's overall philosophy. To overcome this, it's recommended to follow official
documentation, tutorials, and online courses that provide step-by-step guidance.
Practice building small projects and gradually increase the complexity as you gain
more familiarity with React.
2. State Management: As applications grow in size and complexity, managing
application state becomes more challenging. React itself doesn't provide a built-in
solution for state management, so developers often rely on external libraries such as
Redux, MobX, or React Context API. These libraries help manage state in a more
structured and scalable manner. Understanding the principles and patterns of state
management libraries can help overcome this roadblock.
Page 105
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
Remember that overcoming obstacles in React is a natural part of the learning process.
Don't hesitate to seek help from the vibrant React community through forums,
discussion boards, or social media groups. Many developers have faced similar
challenges and can provide guidance and insights to help you overcome any
roadblocks you encounter.
React’s Future: React has established itself as one of the most popular
JavaScript libraries for building user interfaces, and its growth and adoption continue
to be strong. Here are a few aspects that indicate a promising future for React:
Page 106
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
1. Continued Growth: React's popularity and usage have been steadily increasing
over the years, and there is no sign of a decline. Its large community of developers and
extensive ecosystem of libraries, tools, and resources contribute to its continued
growth and support.
2. React Native and Mobile Development: React Native, the framework built on
top of React, has gained significant traction in the mobile app development space. It
enables developers to build native mobile apps for multiple platforms using React and
JavaScript. With the rise of mobile app development and the demand for cross-
platform solutions, React Native is likely to play a crucial role in the future of mobile
development.
3. React Server Components: React Server Components is an experimental
feature introduced by the React team. It aims to bring the benefits of React's
component model to the server-side rendering (SSR) process. This can potentially
improve performance and facilitate seamless code sharing between client and server.
While still in the early stages of development, React Server Components could shape
the future of server-side rendering in React applications.
4. React as a UI Framework: React's component-based architecture and its ability
to create reusable UI components make it a powerful tool for building user interfaces.
With the rise of component-based development and design systems, React is likely to
continue playing a prominent role in the development of UI frameworks and libraries.
5. React Concurrent Mode: React Concurrent Mode is an upcoming feature aimed
at improving the performance and responsiveness of React applications. It introduces
new patterns and APIs to handle asynchronous rendering, allowing components to
work on different priorities and enable more interactive user experiences. Once fully
released, Concurrent Mode has the potential to further enhance React's capabilities
and user experience.
It's worth noting that the web development landscape is constantly evolving, and new
frameworks and technologies emerge over time. However, React's strong community
support, continuous updates, and the backing of Facebook make it well-positioned for
a promising future in the web development space.
Page 107
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
It's always a good practice to stay updated with the latest releases and developments in
the React ecosystem to leverage the newest features and best practices as they become
available.
Keeping up with the changes in ReactJS is important to stay updated with the latest
features, improvements, and best practices. Here are some tips to help you stay
informed:
Page 108
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
latest trends and updates in React. These events often provide valuable insights and
networking opportunities.
6. Follow Influencers and Experts: Follow influential developers, React core team
members, and experts on social media platforms like Twitter and LinkedIn. They often
share their thoughts, insights, and updates about React, keeping you informed about
the latest happenings.
7. Newsletters and Podcasts: Subscribe to React-focused newsletters and podcasts
that provide regular updates and insights about React. Some popular newsletters
include "React Status" (https://react.statuscode.com/) and "React Digest"
(https://reactdigest.net/). Podcasts like "React Podcast" and "React Native Radio" also
cover React-related topics.
8. Open Source Projects and Libraries: Explore open source projects and libraries
built on top of React. These projects often reflect the latest trends and best practices in
React development. Following their repositories and documentation can help you stay
updated.
Remember that React is an evolving ecosystem, and it's important to allocate time
regularly to stay up to date. Experiment with new features, read release notes, and
consider updating your projects to newer versions of React when appropriate. By
actively engaging with the React community and staying informed about the latest
developments, you can ensure that your React skills and projects remain relevant and
up to date.
Working with files in ReactJS typically involves handling file uploads, processing file
data, and interacting with the user's filesystem. Here's a high-level overview of file-
related operations in ReactJS:
1. File Input and Uploads: To enable file uploads, you can use the HTML ‘<input
type="file">’ element. In React, you can create a controlled component that handles
the file input value and listens to changes using the ‘onChange’ event. You can then
Page 109
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
retrieve the selected file(s) from the input element and perform actions like displaying
file information, validating file types/sizes, and initiating file uploads to a server or
cloud storage.
2. File Processing: Once a file is uploaded or selected by the user, you may need
to process its contents. Common scenarios include reading file data, parsing file
formats (e.g., CSV, JSON), or performing client-side transformations. The FileReader
API or third-party libraries like Papa Parse or XLSX can be used to read and process
file data in various formats.
3. File Downloads: React provides ways to initiate file downloads from the client-
side. You can create a link (‘<a>’) element with the desired file URL and set the
‘download’ attribute to specify the desired file name. Clicking on this link triggers the
download. Alternatively, you can use third-party libraries or APIs for more advanced
download functionality, such as generating files dynamically or downloading files
from external sources.
4. Drag and Drop: React allows you to implement drag-and-drop functionality to
enable users to drag files from their filesystem and drop them onto a designated area
in the application. By handling the ‘drag’ and ‘drop’ events, you can retrieve the
dropped files, validate them, and perform actions accordingly.
5. File Validation and Error Handling: When working with files, it's important to
validate user inputs and handle errors gracefully. You can check file types, sizes, and
other properties to ensure they meet your application's requirements. Display
appropriate error messages or feedback to the user if the file is invalid or if any errors
occur during file operations.
6. Third-Party Libraries: React has a vast ecosystem of third-party libraries that
can simplify file-related tasks. Libraries like react-dropzone, react-filepond, and react-
dropzone-uploader provide pre-built components and APIs for handling file uploads
and drag-and-drop functionality. Evaluate these libraries to see if they meet your
specific requirements and integrate them into your React application.
Page 110
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
Remember to consider security aspects when dealing with file uploads and processing.
Implement server-side validation and sanitization to prevent malicious file uploads
and potential security vulnerabilities.
Working with files in ReactJS often involves a combination of JavaScript, HTML, and
CSS, along with the React component lifecycle and state management. By
understanding these concepts and utilizing appropriate libraries and APIs, you can
effectively handle file-related operations in your React applications.
Pure React:
Pure React, also known as Vanilla React, refers to using React without any additional
libraries or frameworks. It means leveraging only the core capabilities and APIs
provided by React itself, without relying on external dependencies like state
management libraries or UI frameworks.
When working with pure React, you primarily use React's core concepts, including
components, JSX, state, and lifecycle methods. Here's an overview of how these key
aspects work in pure React:
Page 111
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
4. Lifecycle Methods: React components have lifecycle methods that are called at
different stages of a component's life, such as mounting, updating, and unmounting.
These methods allow you to perform actions at specific points in the component's
lifecycle, like initializing state, making API calls, or cleaning up resources.
By using these core features of React, you can build interactive user interfaces and
handle user interactions effectively. However, keep in mind that as your application
grows in complexity, you may need to consider additional libraries or patterns for state
management, routing, and other advanced functionalities. Redux, React Router, and
other libraries can be introduced as needed, based on your project requirements.
Using pure React can be beneficial in terms of simplicity, learning the core concepts
deeply, and having full control over your application. It also helps to have a better
understanding of how React works under the hood. However, it's important to strike a
balance between leveraging the power of React itself and utilizing third-party libraries
to enhance productivity and maintainability in larger projects
Pagesetup n ReactJS:
Page 112
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
example, you can define a route for the home page ("/") to render the HomePage
component.
3. Render Pages: In your main application component, typically named App,
import the necessary page components and set up the routing configuration provided
by React Router. Inside the component, use the Router and Route components from
React Router to map the defined routes to their respective page components. This
ensures that the correct page component is rendered based on the current URL.
4. Linking and Navigation: Use the Link component from React Router to create
links between different pages within your application. The Link component generates
anchor tags with proper URL routing, allowing users to navigate between pages
without reloading the entire application. For example, you can use the Link
component to create a navigation bar with links to different pages.
5. Page Content and Functionality: Each page component should contain the
specific content and functionality relevant to that page. Customize the content, layout,
and behavior of each page according to its requirements. You can utilize other React
components, state management techniques, and API integrations as needed for each
page.
By following this approach, you can set up pages in your ReactJS application, enable
routing between them, and define the content and functionality specific to each page.
React Router provides a flexible and powerful way to handle page navigation and
URL routing in React applications, making it easier to create multi-page applications
or single-page applications with multiple views.
The Virtual DOM is a key concept in ReactJS that contributes to its efficient rendering
and performance optimizations. Here's an explanation of what the Virtual DOM is and
how it works:
Page 113
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
mirrors the structure of the real DOM but lacks the ability to directly interact with the
browser.
2. How does the Virtual DOM work? When a React component's state or props
change, React creates a new Virtual DOM representation of the component and
compares it with the previous Virtual DOM. This process is known as reconciliation
or diffing.
3. Reconciliation process: React's reconciliation process involves three main
steps:
a. Diffing: React compares the new Virtual DOM with the previous one, identifying
the differences between them. It efficiently determines which parts of the UI need to
be updated.
b. Re-rendering: React updates only the necessary parts of the real DOM based on the
differences identified during the diffing process. It minimizes the number of actual
changes made to the DOM.
c. Patching: React updates the affected elements in the real DOM by applying the
necessary changes in an optimized manner, resulting in an updated UI.
4. Benefits of the Virtual DOM:
Performance Optimization: The Virtual DOM allows React to minimize
costly direct manipulations of the real DOM by efficiently updating only the
necessary parts. This helps to improve the overall performance of React
applications.
Reusability and Maintainability: React's component-based architecture,
combined with the Virtual DOM, enables the reusability of components and
modular development. Components can be composed, updated independently,
and easily maintained.
Cross-platform Support: The Virtual DOM works consistently across
different platforms and browsers, providing a unified approach to UI rendering
and making React suitable for multi-platform development.
It's important to note that the Virtual DOM is an implementation detail of React. It
abstracts away the low-level manipulations of the real DOM, making it easier for
Page 114
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
developers to work with and reason about UI updates. However, understanding the
Virtual DOM can help in optimizing React applications and utilizing React's
performance features effectively.
React Elements: In ReactJS, React Elements are the building blocks used to
describe and represent the UI hierarchy. They are lightweight JavaScript objects that
represent components, DOM elements, or fragments. React Elements are created
using JSX or React's createElement() function.
Here's an overview of React Elements and how they are used in React:
Page 115
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
3. Rendering React Elements: React Elements are typically rendered to the actual
DOM using ReactDOM's render() function. The render() function takes a React
Element and a target DOM node as arguments and inserts the rendered output into the
target node. For example:
4. const element = <h1>Hello, World!</h1>;
ReactDOM.render(element, document.getElementById('root'));
4. React Components and React Elements: React Components are reusable and
self-contained units of UI logic. When you define a component, you create React
Elements that represent instances of that component. Components are used to
compose the UI hierarchy by creating and nesting React Elements.
5. Immutable Nature: React Elements are immutable, meaning they cannot be
modified directly. Instead, when a change occurs in the application state or props,
React creates a new set of React Elements and performs a reconciliation process to
update the UI efficiently.
React Elements form the foundation of React's declarative approach to building user
interfaces. They describe the desired UI structure and appearance, and React takes
care of efficiently updating and rendering the UI based on changes to the Elements or
underlying data.
React DOM:
ReactDOM is a package in React that provides the methods and APIs for rendering
React components to the actual browser DOM. It acts as the bridge between React's
virtual representation of the UI (Virtual DOM) and the real DOM.
Page 116
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
In this example, the element is rendered and inserted into the DOM element with the
id 'root'.
4. Other Methods: ReactDOM provides additional methods for working with the
DOM, such as:
ReactDOM.findDOMNode(): This method returns the DOM node
associated with a mounted React component. It should be used with caution as
it is considered an escape hatch and is discouraged in most cases.
ReactDOM.createPortal(): This method allows rendering React
components into a different DOM subtree, typically outside the current
component's hierarchy. It is useful for scenarios like modals or overlays.
Overall, ReactDOM serves as the interface between React components and the
browser's DOM. It facilitates the rendering of React components, updates to the UI
based on changes in React Elements, and the management of component lifecycles.
Children:
Page 117
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
Children
In React, the concept of "children" refers to the content that is nested inside a
component. It allows you to pass arbitrary content or components as props to a parent
component and render them within the parent's JSX structure.
return (
<div>
<h1>Parent Component</h1>
{children}
</div>
); };
return (
<ParentComponent>
<button>Click me!</button>
</ParentComponent>
); };
Page 118
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
When the’ ParentComponent ‘is rendered, the children will be inserted at the
location of ‘{children}’ in the JSX. So, the rendered output will look like this:
The’ children’ prop can also be an array or multiple elements. For example:
<ParentComponent>
<p>First child</p>
<p>Second child</p>
</ParentComponent>
In this case, the ‘children’ prop will be an array of two paragraph elements, and they
will be rendered accordingly.
Using the concept of children, you can create reusable components that wrap and
render different content depending on how they are used. It provides a flexible way to
compose components and build complex UI structures in React.
In React, you can construct elements with data by dynamically generating and
rendering components based on the data you have. This is commonly done using
JavaScript's array methods, such as’ map()’, to iterate over the data and generate a
collection of components.
const data = [
Page 119
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
];
return (
<div>
<h1>User List</h1>
<ul>
{data.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
};
In this example, we have an array called ‘data’ that contains user objects. The ‘App’
component renders a list of users by mapping over the ‘data’ array using the ‘map()’
method. For each user, a ‘<li>’ element is generated with the user's name as the
content. The ‘key’ prop is set to the ‘id’ property of each user, which helps React
efficiently update and re-render the list.
<div>
Page 120
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
<h1>User List</h1>
<ul>
<li>John</li>
<li>Jane</li>
<li>Bob</li>
</ul>
</div>
By dynamically generating elements with data, you can easily handle lists, tables, or
any other structured data in your React components. This approach allows for
flexibility and reusability, as the components can adapt to different datasets.
By dynamically generating elements with data, you can easily handle lists, tables, or
any other structured data in your React components. This approach allows for
flexibility and reusability, as the components can adapt to different datasets.
React Components:
In React, components are the building blocks of a user interface. They are reusable,
self-contained pieces of code that encapsulate a specific functionality and render a part
of the UI. React components can be either class-based or function-based.
Class-based components (prior to React 16.8) are defined using ES6 classes and
extend the ‘React.Component’ class. They have a ‘render() ‘method that returns the
JSX to be rendered. Here's an example of a class-based component:
render() {
Page 121
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
};
Components can also accept and handle props, which are essentially the properties or
configuration values passed to a component from its parent component. Props allow
components to be dynamic and customizable. Here's an example of a component that
accepts props:
};
};
In this example, the ‘Greeting’ component receives the ‘name’ prop and renders a
personalized greeting.
Page 122
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
Components can be composed together to create complex UI structures. They can also
maintain an internal state using the ‘useState’ hook (in function components) or by
extending the ‘React.Component’ class and using the ‘state’ property (in class
components). State allows components to manage and update their data over time.
React components follow a unidirectional data flow, where the parent component
passes data down to child components via props. Changes in the data are propagated
from the top-level component down to its children, triggering re-renders as needed.
DOM Rendering:
DOM rendering in React refers to the process of taking React components and
rendering them as elements in the browser's Document Object Model (DOM). React
uses a virtual DOM (a lightweight copy of the actual DOM) to efficiently update and
reconcile changes in the UI.
Once the virtual DOM tree is constructed, React compares it with the previous version
of the virtual DOM (from the previous render) to identify any differences. This
process is known as reconciliation.
React determines the minimal set of changes needed to update the actual DOM based
on the differences found during reconciliation. It then applies these changes to the real
DOM, resulting in an updated user interface.
Page 123
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
The ReactDOM library provides the render() function, which is used to render a
React component or element onto the real DOM. Here's an example:
};
In this example, we have a simple’ App ‘component that renders an ‘<h1>’ element
with the text "Hello, world!". The ‘ReactDOM.render()’ function is used to render
the ‘App’ component into the DOM. The resulting output is inserted into the element
with the ‘id’, "root" in the HTML file.
React components are designed to be reusable and composable, allowing you to build
complex UI structures by combining smaller components. When changes occur to the
component's state or props, React efficiently updates only the necessary parts of the
DOM, resulting in better performance compared to traditional manual DOM
manipulation.
By using the virtual DOM and reconciliation process, React abstracts away the
complexities of directly interacting with the real DOM, making it easier to build
interactive and responsive user interfaces.
Factories:
Page 124
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
1. Component Factories: These are functions that create and return React
components. They can be used to generate components with specific props or
behaviors. Here's an example of a component factory:
<div>
<h1>{props.title}</h1>
<p>{propValue}</p>
</div>
);
};
Page 125
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
};
};
// Usage:
return <div>{props.message}</div>;
};
};
// Usage:
};
Page 126
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
Page 127
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
Faster Processing: SAX can be faster than DOM for large XML files since it
processes data in a streaming manner without the need to construct and store the entire
document tree.
Suitable for Large Documents: SAX is suitable for scenarios where memory
usage is a concern or when you need to process large XML documents sequentially
without requiring random access to the entire document structure.
The choice between DOM and SAX depends on the specific requirements of your
application. Use DOM when you need random access, modification, and querying
capabilities for XML documents. On the other hand, if you have memory constraints
or need to process large XML files sequentially, SAX provides a lightweight and
efficient solution for parsing and processing XML dataV
UNIT-V
MongoDB:
Page 128
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
4. Query Language: MongoDB uses a powerful and flexible query language that
allows you to retrieve specific documents from a collection. The query language
supports a wide range of operators for filtering, sorting, and aggregating data.
5. Indexing: MongoDB supports indexing to improve query performance. Indexes
are data structures that store a subset of the data in a more efficient format, enabling
faster data retrieval.
6. Replication: MongoDB provides replication for high availability and data
redundancy. Replication allows you to create multiple copies of data across different
servers, ensuring that if one server fails, another can take its place.
7. Sharding: MongoDB supports sharding, which allows you to distribute data
across multiple servers or clusters. Sharding enables horizontal scaling and can handle
large amounts of data by dividing it into smaller chunks called shards.
8. Geospatial Indexing: MongoDB has built-in support for geospatial data,
allowing you to store and query location-based information such as points, polygons,
and distances.
9. Aggregation Framework: MongoDB provides a powerful Aggregation
Framework that allows you to perform complex data processing and analysis
operations, including grouping, sorting, filtering, and transforming data.
10. Integration with Programming Languages: MongoDB offers official drivers for
various programming languages, making it easy to interact with the database from
applications written in languages like JavaScript, Python, Java, C#, and more.
Architecture of Mongodb
Page 129
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
that allows for horizontal scaling and efficient handling of large volumes of data. Here
are the key components and concepts in the architecture of MongoDB:
Page 130
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
Features of mongodb
MongoDB offers a wide range of features that make it a popular choice for modern
application development. Here are some key features of MongoDB:
Page 131
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
scalability as data volumes grow. It enables applications to handle high traffic and
large datasets by dividing data into smaller subsets called shards.
4. High Availability: MongoDB provides high availability through replica sets. A
replica set is a group of MongoDB nodes that maintain multiple copies of the data. If a
primary node fails, a secondary node automatically takes over, ensuring continuous
availability of the database.
5. Indexing and Querying: MongoDB supports various types of indexes, including
single-field, compound, geospatial, and text indexes. Indexing improves query
performance by enabling efficient data retrieval based on specified criteria.
MongoDB's flexible query language allows for powerful querying capabilities,
including rich filtering, sorting, and aggregation operations.
6. Full-Text Search: MongoDB offers built-in full-text search capabilities that
allow you to perform complex text-based queries on textual data within documents. It
supports text indexes and powerful search operators to perform text search efficiently.
7. Aggregation Framework: MongoDB provides a powerful Aggregation
Framework that allows for data transformation, grouping, filtering, and analysis
operations. It enables developers to perform complex data processing within the
database, reducing the need for additional data processing layers.
8. Geospatial Capabilities: MongoDB has built-in support for geospatial data and
offers various geospatial operators and indexes. This enables storing and querying of
location-based data, making it suitable for applications involving geolocation and
mapping.
9. ACID Transactions: Starting from version 4.0, MongoDB supports multi-
document ACID transactions, allowing you to maintain data consistency and integrity
across multiple operations. Transactions ensure that a group of database operations
either succeeds in its entirety or fails entirely.
10. Security: MongoDB provides robust security features, including authentication,
authorization, and role-based access control (RBAC). It also supports Transport Layer
Security (TLS) encryption for secure communication between clients and the
database.
Page 132
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
11. Integration and Ecosystem: MongoDB offers official drivers and libraries for
various programming languages, making it easy to integrate MongoDB with different
application stacks. Additionally, MongoDB has a thriving ecosystem with a wide
range of tools, frameworks, and community resources to support developers.
Examples of mongodb
Page 133
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
mongo
Page 134
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
2. Create a Database: In MongoDB, you can create a new database by using the
use command. If the database doesn't exist, MongoDB will create it when you insert
data into it. For example, to create a database called "mydatabase", run the following
command:
Shell copycode
Use mydatabase
3. Create a Collection: Once you have a database, you can create a collection by
simply starting to insert documents into it. When you insert the first document,
MongoDB will create the collection if it doesn't already exist. For example, to create a
collection called "mycollection" and insert a document into it, run the following
command
" })
4. Verify Collection Creation: To verify that the collection has been created, you
can use the show collections command or db.getCollectionNames() method. For
example:
show collections
or
Page 135
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
This will display a list of collections in the current database, and you should see
"mycollection" in the list.
Congratulations! You have now created a database and a collection in MongoDB. You
can continue inserting more documents into the collection or perform various
operations like querying, updating, and deleting documents within the collection.
When deploying an application that uses MongoDB, you need to consider the
following steps:
Page 136
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
Remember to follow best practices for security, performance, and scalability when
deploying your application. It's also important to consider backup and disaster
recovery strategies for your MongoDB database to safeguard your data.
Web hosting and domains are essential components for making a website accessible
on the internet. Here's a brief overview of each:
1. Web Hosting: Web hosting involves the storage and serving of website files and
data on servers that are connected to the internet. When you choose a web hosting
service, you essentially rent space on a server where you can store your website files,
databases, and other resources.
Page 137
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
Shared Hosting: Multiple websites are hosted on a single server, sharing its
resources.
Virtual Private Server (VPS) Hosting: Provides dedicated resources within a
shared environment by creating virtual servers.
Dedicated Hosting: Offers an entire physical server dedicated to a single
website or application.
Cloud Hosting: Utilizes a network of interconnected servers to distribute
resources and ensure scalability.
Web hosting providers typically offer various plans with different features and pricing
options. When selecting a web hosting provider, consider factors like reliability,
performance, security measures, customer support, and the specific needs of your
website or application.
2. Domain: A domain is the unique address or URL that users type into their
browsers to access a website. For example, "example.com" is a domain. Domain
names provide a more user-friendly way to identify websites instead of using IP
addresses.
Page 138
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
It's worth noting that some web hosting providers also offer domain registration
services, simplifying the process by managing both web hosting and domain
management under a single provider.
In summary, web hosting provides the infrastructure and resources for storing and
serving website files, while domains give your website a unique address on the
internet. These two components work together to make your website accessible to
users worldwide
1. Choose a Cloud Platform: Select a cloud platform that suits your application's
requirements. Popular cloud platforms include Amazon Web Services (AWS),
Microsoft Azure, Google Cloud Platform (GCP), and IBM Cloud. Consider factors
like pricing, available services, scalability options, and integration capabilities.
2. Set Up an Account: Create an account on the chosen cloud platform and set up
the necessary billing and account settings.
3. Prepare Your Application: Ensure your application is ready for deployment.
This involves packaging your application files, including any dependencies, and
preparing any necessary configuration files.
4. Select Deployment Method: Cloud platforms offer various deployment
methods, depending on your application's architecture and specific requirements:
Page 139
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
Page 140
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639
It's important to refer to the documentation and resources provided by the specific
cloud platform you choose, as the deployment process may vary depending on the
platform and services you utilize.
UNIT-IV
Here are some key concepts and principles associated with RESTful web services:
Page 141
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)