AWP Lab Manual
AWP Lab Manual
Theory
CSS tutorial or CSS 3 tutorial provides basic and advanced concepts of CSS technology.
Our CSS tutorial is developed for beginners and professionals. The major points of CSS are
given below:
CSS stands for Cascading Style Sheet.
CSS is used to design HTML tags.
CSS is a widely used language on the web.
HTML, CSS and JavaScript are used for web designing. It helps the web designers to
apply style on HTML tags.
What is CSS?
CSS stands for Cascading Style Sheets. It is a style sheet language which is used to describe
the look and formatting of a document written in markup language. It provides an additional
feature to HTML. It is generally used with HTML to change the style of web pages and user
interfaces. It can also be used with any kind of XML documents including plain XML, SVG
and XUL.
CSS is used along with HTML and JavaScript in most websites to create user interfaces for
web applications and user interfaces for many mobile applications.
What does CSS DO?
You can add new looks to your old HTML documents.
You can completely change the look of your website with only a few changes in CSS
code.
CSS Selector
CSS selectors are used to select the content you want to style. Selectors are the part of CSS
rule set. CSS selectors select HTML elements according to its id, class, type, attribute etc.
There are several different types of selectors in CSS.
1. CSS Element Selector
2. CSS Id Selector
3. CSS Class Selector
4. CSS Universal Selector
5. CSS Group Selector
CSS Id Selector
The id selector selects the id attribute of an HTML element to select a specific element. An id
is always unique within the page so it is chosen to select a single, unique element.
It is written with the hash character (#), followed by the id of the element.
As you can see, you need to define CSS properties for all the elements. It can be grouped in
following ways:
h1,h2,p {
text-align: center;
color: blue;
}
Example:
<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1>Hello Javatpoint.com</h1>
<h2>Hello Javatpoint.com (In smaller font)</h2>
Gandhinagar Institute of Technology 3161611 AWP
<p>This is a paragraph.</p>
</body>
</html>
Output:
Hello Javatpoint.com
CSS is added to HTML pages to format the document according to information in the style
sheet. There are three ways to insert CSS in HTML documents.
1. Inline CSS
2. Internal CSS
3. External CSS
Inline CSS
Inline CSS is used to apply CSS on a single line or element.
For example:
1. <p style="color:blue">Hello CSS</p>
The inline CSS is also a method to insert style sheets in HTML document. This method
mitigates some advantages of style sheets so it is advised to use this method sparingly.
If you want to use inline CSS, you should use the style attribute to the relevant tag.
Syntax:
Example:
Output:
Internal CSS
Internal CSS is used to apply CSS on a single document or page. It can affect all the elements
of the page. It is written inside the style tag within head section of html.
Example:
<style>
p{color:blue}
</style>
External CSS
External CSS is used to apply CSS on multiple pages or all pages. Here, we write all the CSS
code in a css file. Its extension must be .css for example style.css.
Example:
1. p{color:blue}
You need to link this style.css file to your html pages like this:
1. <link rel="stylesheet" type="text/css" href="style.css">
The link tag must be used inside head section of html.
The external style sheet is generally used when you want to make changes on multiple pages.
It is ideal for this condition because it facilitates you to change the look of the entire web site
by changing just one file.
It uses the <link> tag on every pages and the <link> tag should be put inside the head section.
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
The external style sheet may be written in any text editor but must be saved with a .css
extension. This file should not contain HTML elements.
File: mystyle.css
body {
background-color: lightblue;
}
Note: You should not use a space between the property value and the unit. For example: It
should be margin-left: 20px not margin-left: 20 px.
Exercise:
1. Write CSS script for scroll value of the background-attachment property, which is the
default behavior. So when the page is scrolled, the background scrolls with it.
2. Write CSS script for the border of the paragraph elements with the image. In the first
paragraph, we are specifying the single value (i.e., round) of the border-image-repeat
property, whereas in the second paragraph, we are specifying two values (round,
stretch) of it, the first value for the horizontal sides and second value for the vertical
sides.
Review Questions:
1. What are the CSS frameworks?
2. Why background and color are the separate properties if they should always be set
together?
3. What is the use of ruleset?
JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your web page,
but it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags
as a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes −
Language − this attribute specifies what scripting language you are using. Typically,
its value will be JavaScript. Although recent versions of HTML (and XHTML, its
successor) have phased out the use of this attribute.
Type − this attribute is what is now recommended to indicate the scripting language in
use and its value should be set to "text/javascript".
So your JavaScript segment will look like −
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>
Your First JavaScript Code
Let us take a sample example to print out "Hello World". We added an optional HTML
comment that surrounds our JavaScript code. This is to save our code from a browser
that does not support JavaScript. The comment ends with a "//-->". Here "//" signifies
a comment in JavaScript, so we add that to prevent a browser from reading the end of
the HTML comment as a piece of JavaScript code. Next, we call a
function document.write which writes a string into our HTML document.
This function can be used to write text, HTML, or both. Take a look at the following
code.
Example:
<html>
<body>
<script language = "javascript" type = "text/javascript">
Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords, variables,
function names, and any other identifiers must always be typed with a consistent capitalization
of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.
NOTE − Care should be taken while writing variable and function names in JavaScript.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
JavaScript Variables
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Arithmetic Operators: JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then –
Table 1: Arithmetic Operators
1
+ (Addition)
Adds two operands
Ex: A + B will give 30
2
- (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3
* (Multiplication)
Multiply both operands
Ex: A * B will give 200
4
/ (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
5
% (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6
++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give
"a10"
Comparison Operators:
1
= = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition becomes
true.
Ex: (A == B) is not true.
2
!= (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then the
condition becomes true.
Ex: (A != B) is true.
3
> (Greater than)
Checks if the value of the left operand is greater than the value of the right operand, if
yes, then the condition becomes true.
Ex: (A > B) is not true.
4
< (Less than)
Checks if the value of the left operand is less than the value of the right operand, if yes,
then the condition becomes true.
Ex: (A < B) is true.
5
>= (Greater than or Equal to)
6
<= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the right
operand, if yes, then the condition becomes true. Ex: (A <= B) is true.
Logical Operators:
1
&& (Logical AND)
If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
2
|| (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3
! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
operator will make it false.
Ex: ! (A && B) is false.
Bitwise Operators:
1
& (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.
2
| (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
3
^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer arguments.
Exclusive OR means that either operand one is true or operand two is true, but not both.
Ex: (A ^ B) is 1.
4
~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
5
<< (Left Shift)
It moves all the bits in its first operand to the left by the number of places specified in the
second operand. New bits are filled with zeros. Shifting a value left by one position is
equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4,
and so on.
Ex: (A << 1) is 4.
6
>> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by the number of
bits specified by the right operand. Ex: (A >> 1) is 1.
7
>>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the left are
always zero. Ex: (A >>> 1) is 1.
1
= (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
2
+= (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
3
−= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C - A
4
*= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A
5
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left operand.
Ex: C /= A is equivalent to C = C / A
6
%= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
Note − same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=,
|= and ^=.
? : (Conditional )
If Condition is true? Then value X : Otherwise value Y
typeof Operator:
The type of operator is a unary operator that is placed before its single operand, which can be
of any type. Its value is a string indicating the data type of the operand.
The type of operator evaluates to "number", "string", or "Boolean" if its operand is a number,
string, or Boolean value and returns true or false based on the evaluation.
Table 6: Return values for the type of Operator
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
JavaScript - if...else Statement
if statement
if...else statement
if...else if... statement.
if statement
The if statement is the fundamental control statement that allows JavaScript to make decisions
and execute statements conditionally.
Syntax:
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
Gandhinagar Institute of Technology 3161611 AWP
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s)
are executed. If the expression is false, then no statement would be not executed. Most of the
times, you will use comparison operators while making decisions.
if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.
Syntax:
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s)
in the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else
block are executed.
Syntax:
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a
part of the else clause of the previous statement. Statement(s) are executed based on the true
condition, if none of the conditions is true, then the else block is executed.
JavaScript for...in loop
The for...in loop is used to loop through an object's properties. As we have not discussed
Objects yet, you may not feel comfortable with this loop. But once you understand how objects
behave in JavaScript, you will find this loop very useful.
Syntax:
The syntax of ‘for..in’ loop is −
for (variablename in object) {
Gandhinagar Institute of Technology 3161611 AWP
statement or block to execute
}
In each iteration, one property from object is assigned to variablename and this loop
continues till all the properties of the object are exhausted.
Example:
Try the following example to implement ‘for-in’ loop. It prints the web
browser’s Navigator object.
<html>
<body>
<script type = "text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
//-->
</script>
<p>Set the variable to different object and then try...</p>
</body>
</html>
JavaScript - Loop Control:
JavaScript provides full control to handle loops and switch statements. There may be a
situation when you need to come out of a loop without reaching its bottom. There may also
be a situation when you want to skip a part of your code block and start the next iteration of
the loop.
To handle all such situations, JavaScript provides break and continue statements. These
statements are used to immediately come out of any loop or to start the next iteration of any
loop respectively.
Function Definition
Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax:
The basic syntax is shown here.
<script type = "text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>
Example:
Try the following example. It defines a function called sayHello that takes no parameters –
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello there");
}
//-->
</script>
Calling a Function:
To invoke a function somewhere later in the script, you would simply need to write the name
of that function as shown in the following code.
Function Parameters:
Till now, we have seen functions without parameters. But there is a facility to pass different
parameters while calling a function. These passed parameters can be captured inside the
function and any manipulation can be done over those parameters. A function can take
multiple parameters separated by comma.
Example:
Try the following example. We have modified our sayHello function here. Now it takes two
parameters.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>
Example:
Try the following example. It defines a function that takes two parameters and concatenates
them before returning the resultant in the calling program.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Review Questions:
1. Can an anonymous function be assigned to a variable?
2. If we want to return the character from a specific index which method is used?
3. What is the difference between JavaScript and JScript?
Theory
What is an Event?
JavaScript's interaction with HTML is handled through events that occur when the user or
the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an
event. Other examples include events like pressing any key, closing a window, resizing a
window, etc.
Developers can use these events to execute JavaScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and
virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element
contains a set of events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event Reference.
Here we will see a few examples to understand a relation between Event and JavaScript −
Example:
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.
Here we are calling a validate() function before submitting a form data to the webserver.
If validate() function returns true, the form will be submitted, otherwise it will not submit the
data.
Example:
<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body></html>
These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element. Try the following
Example:
<html>
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless
protocol. But for a commercial website, it is required to maintain session information among
different pages. For example, one user registration ends after completing many pages. But
how to maintain users' session information across all the web pages.
In many situations, using cookies is the most efficient method of remembering and tracking
preferences, purchases, commissions, and other information required for better visitor
experience or site statistics.
Gandhinagar Institute of Technology 3161611 AWP
How It Works?
Your server sends some data to the visitor's browser in the form of a cookie. The browser may
accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now,
when the visitor arrives at another page on your site, the browser sends the same cookie to the
server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.
Cookies are a plain text data record of 5 variable-length fields −
Expires − the date the cookie will expire. If this is blank, the cookie will expire when
the visitor quits the browser.
Domain − the domain name of your site.
Path − the path to the directory or web page that set the cookie. This may be blank if
you want to retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure", then the cookie may only be retrieved
with a secure server. If this field is blank, no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key-value pairs
Cookies were originally designed for CGI programming. The data contained in a cookie is
automatically transmitted between the web browser and the web server, so CGI scripts on the
server can read and write cookie values that are stored on the client.
JavaScript can also manipulate cookies using the cookie property of the Document object.
JavaScript can read, create, modify, and delete the cookies that apply to the current web page.
Storing Cookies
The simplest way to create a cookie is to assign a string value to the document.cookie object,
which looks like this.
document.cookie = "key1 = value1;key2 = value2;expires = date";
Here the expires attribute is optional. If you provide this attribute with a valid date or time,
then the cookie will expire on a given date or time and thereafter, the cookies' value will not
be accessible.
Note − Cookie values may not include semicolons, commas, or whitespace. For this reason,
you may want to use the JavaScript escape() function to encode the value before storing it in
the cookie. If you do this, you will also have to use the corresponding unescape() function
when you read the cookie value.
Example:
<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
Reading Cookies:
Reading a cookie is just as simple as writing one, because the value of the document.cookie
object is the cookie. So you can use this string whenever you want to access the cookie. The
document.cookie string will keep a list of name=value pairs separated by semicolons,
where name is the name of a cookie and value is its string value.
You can use strings' split() function to break a string into key and values as follows −
Example:
<html>
<head>
<script type = "text/javascript">
<!--
function ReadCookie() {
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
You can extend the life of a cookie beyond the current browser session by setting an expiration
date and saving the expiry date within the cookie. This can be done by setting
the ‘expires’ attribute to a date and time.
Example:
<html>
<head>
Deleting a Cookie
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie
return nothing. To do this, you just need to set the expiry date to a time in the past.
You might have encountered a situation where you clicked a URL to reach a page X but
internally you were directed to another page Y. It happens due to page redirection. This
concept is different from JavaScript Page Refresh.
There could be various reasons why you would like to redirect a user from the original page.
We are listing down a few of the reasons −
Example:
It is quite simple to do a page redirect using JavaScript at client side. To redirect your site
visitors to a new page, you just need to add a line in your head section as follows.
<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
window.location = "https://www.tutorialspoint.com";
}
//-->
</script>
</head>
<body>
<p>Click the following button, you will be redirected to home page.</p>
<form>
<input type = "button" value = "Redirect Me" onclick = "Redirect();" />
</form>
</body>
</html>
Example:
You can show an appropriate message to your site visitors before redirecting them to a new
page. This would need a bit time delay to load a new page. The following example shows how
to implement the same. Here setTimeout() is a built-in JavaScript function which can be used
to execute another function after a given time interval.
<body>
<script type = "text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
Output:
Book name is : Perl
Book author is : Mohtashim
Example:
This example demonstrates how to create an object with a User-Defined Function.
Here this keyword is used to refer to the object that has been passed to a function.
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>
Output:
Book title is : Perl
Book author is : Mohtashim
Defining Methods for an Object
The previous examples demonstrate how the constructor creates the object and assigns
properties. But we need to complete the definition of an object by assigning methods to it.
Example:
Try the following example; it shows how to add a function along with an object.
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
// Define a function which will work as a method
function addPrice(amount) {
this.price = amount;
}
function book(title, author) {
this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type = "text/javascript">
Gandhinagar Institute of Technology 3161611 AWP
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script> </body></html>
Output:
Book title is: Perl
Book author is: Mohtashim
Book price is: 100
The 'with' Keyword
The ‘with’ keyword is used as a kind of shorthand for referencing an object's properties or
methods.
The object specified as an argument to with becomes the default object for the duration of the
block that follows. The properties and methods for the object can be used without naming the
object.
Syntax: The syntax for with object is as follows;
with (object)
{ properties used without the object name and dot
}
JavaScript Native Objects
JavaScript has several built-in or native objects. These objects are accessible anywhere in
your program and will work the same way in any browser running in any operating system.
Scaffolding − Bootstrap provides a basic structure with Grid System, link styles, and
background. This is is covered in detail in the section Bootstrap Basic Structure
CSS − Bootstrap comes with the feature of global CSS settings, fundamental HTML
elements styled and enhanced with extensible classes, and an advanced grid system.
This is covered in detail in the section Bootstrap with CSS.
Components − Bootstrap contains over a dozen reusable components built to provide
iconography, dropdowns, navigation, alerts, pop-overs, and much more. This is
covered in detail in the section Layout Components.
JavaScript Plugins − Bootstrap contains over a dozen custom jQuery plugins. You
can easily include them all, or one by one. This is covered in details in the
section Bootstrap Plugins.
Customize − You can customize Bootstrap's components, LESS variables, and jQuery
plugins to get your very own version.
It is very easy to setup and start using Bootstrap. This chapter will explain how to
download and setup Bootstrap. We will also discuss the Bootstrap file structure, and
demonstrate its usage with an example.
Download Bootstrap
You can download the latest version of Bootstrap from https://getbootstrap.com/.
When you click on this link, you will get to see a screen as below −
Here you can see two buttons −
Download Bootstrap − Clicking this, you can download the precompiled and minified
versions of Bootstrap CSS, JavaScript, and fonts. No documentation or original source
code files are included.
Download Source − Clicking this, you can get the latest Bootstrap LESS and
JavaScript source code directly from GitHub.
File structure
Precompiled Bootstrap
Once the compiled version Bootstrap is downloaded, extract the ZIP file, and you will see the
following file/directory structure −
HTML Template
<head>
<title>Bootstrap 101 Template</title>
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --
>
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src = "https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src = "https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body>
<h1>Hello, world!</h1>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src = "js/bootstrap.min.js"></script>
</body>
</html>
Here you can see the jquery.js, bootstrap.min.js and bootstrap.min.css files that are
included to make a normal HTM file to the Bootstrapped Template. Just make sure to include
jQuery library before you include Bootstrap library.
Grid systems are used for creating page layouts through a series of rows and columns that
house your content. Here's how the Bootstrap grid system works −
Rows must be placed within a .container class for proper alignment and padding.
Use rows to create horizontal groups of columns.
Content should be placed within the columns, and only columns may be the immediate
children of rows.
Predefined grid classes like .row and .col-xs-4 are available for quickly making grid
layouts. LESS mixins can also be used for more semantic layouts.
Columns create gutters (gaps between column content) via padding. That padding is
offset in rows for the first and the last column via negative margin on .rows.
Grid columns are created by specifying the number of twelve available columns you
wish to span. For example, three equal columns would use three .col-xs-4.
Bootstrap - Tables
Bootstrap provides a clean layout for building tables. Some of the table elements supported
by Bootstrap are −
1
<table>
Wrapping element for displaying data in a tabular format
3
<tbody>
Container element for table rows (<tr>) in the body of the table.
4
<tr>
Container element for a set of table cells (<td> or <th>) that appears on a single row.
5
<td>
Default table cell.
6
<th>
Special table cell for column (or row, depending on scope and placement) labels. Must be
used within a <thead>
7
<caption>
Description or summary of what the table holds.
Along with the base table markup and the .table class, there are a few additional classes that
you can use to style the markup. Following sections will give you a glimpse of all these
classes.
Striped Table
By adding the .table-striped class, you will get stripes on rows within the <tbody> as seen in
the following example −
Example:
<table class = "table table-striped">
<caption>Striped Table Layout</caption>
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>Pincode</th>
</tr>
</thead>
<tr>
<td>Uma</td>
<td>Pune</td>
<td>411027</td>
</tr>
</tbody>
</table>
Output:
Bootstrap - Forms
Form Layout
Inline Form
To create a form where all of the elements are inline, left aligned and labels are alongside, add
the class .form-inline to the <form> tag.
Example:
<form class = "form-inline" role = "form">
<div class = "form-group">
<label class = "sr-only" for = "name">Name</label>
<input type = "text" class = "form-control" id = "name" placeholder = "Enter Name">
</div>
<div class = "form-group">
<label class = "sr-only" for = "inputfile">File input</label>
<input type = "file" id = "inputfile">
</div>
<div class = "checkbox">
<label><input type = "checkbox"> Check me out</label>
</div>
<button type = "submit" class = "btn btn-default">Submit</button>
</form>
Exercise:
Create a registration form using bootstrap. According below figure.
Review Questions:
1. Enlist key components of Bootstrap?
2. Give an example of a basic grid structure in Bootstrap.
3. What is column ordering in Bootstrap?
AngularJS Directives
The AngularJS framework can be divided into three major parts −
ng-app − This directive defines and links an AngularJS application to HTML.
ng-model − This directive binds the values of AngularJS application data to HTML
input controls.
ng-bind − This directive binds the AngularJS application data to HTML tags.
The Model
The model is responsible for managing application data. It responds to the request from view
and to the instructions from controller to update itself.
The View
A presentation of data in a particular format, triggered by the controller's decision to present
the data. They are script-based template systems such as JSP, ASP, PHP and very easy to
integrate with AJAX technology.
The Controller
The controller responds to user input and performs interactions on the data model objects. The
controller receives input, validates it, and then performs business operations that modify the
state of the data model.
AngularJS is a MVC based framework. In the coming chapters, we will see how AngularJS
uses MVC methodology.
AngularJS - First Application
Before creating actual Hello World ! application using AngularJS, let us see the parts of a
AngularJS application. An AngularJS application consists of following three important parts
ng-app − This directive defines and links an AngularJS application to HTML.
ng-model − This directive binds the values of AngularJS application data to HTML
input controls.
ng-bind − This directive binds the AngularJS Application data to HTML tags.
<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
</div>
Example:
The following example shows the use of all the above-mentioned directives.
testAngularJS.htm
<html>
<head>
<title>AngularJS Directives</title>
Gandhinagar Institute of Technology 3161611 AWP
</head>
<body>
<h1>Sample Application</h1>
<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'},
{locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]">
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
<p>List of Countries with locale:</p>
<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
</div>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</body>
</html>
AngularJS - Controllers
AngularJS application mainly relies on controllers to control the flow of data in the
application. A controller is defined using ng-controller directive. A controller is a JavaScript
object that contains attributes/properties, and functions. Each controller accepts $scope as a
parameter, which refers to the application/module that the controller needs to handle.
<div ng-app = "" ng-controller = "studentController">
...
</div>
Here, we declare a controller named studentController, using the ng-controller directive. We
define it as follows
Example:
<script>
function studentController($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
AngularJS - Modules
AngularJS supports modular approach. Modules are used to separate logic such as services,
controllers, application etc. from the code and maintain the code clean. We define modules in
separate js files and name them as per the module.js file. In the following example, we are
going to create two modules −
Application Module − used to initialize an application with controller(s).
Controller Module − used to define the controller.
Application Module
Here is a file named mainApp.js that contains the following code −
var mainApp = angular.module("mainApp", []);
Here, we declare an application mainApp module using angular.module function and pass an
empty array to it. This array generally contains dependent modules.
Controller Module
studentController.js
Example:
mainApp.controller("studentController", function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67}
],
fullName: function() {
var studentObject;
Gandhinagar Institute of Technology 3161611 AWP
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
Here, we declare a controller studentController module using mainApp.controller function.
Use Modules
<div ng-app = "mainApp" ng-controller = "studentController">
...
<script src = "mainApp.js"></script>
<script src = "studentController.js"></script>
</div>
Here, we use application module using ng-app directive, and controller using ngcontroller
directive. We import the mainApp.js and studentController.js in the main HTML page.
Example
The following example shows use of all the above mentioned modules.
testAngularJS.htm
Example:
<html>
<head>
<title>Angular JS Modules</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src = "/angularjs/src/module/mainApp.js"></script>
<script src = "/angularjs/src/module/studentController.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "studentController">
<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input type = "text" ng-model = "student.firstName"></td>
</tr>
<tr>
<td>Enter last name: </td>
<td><input type = "text" ng-model = "student.lastName"></td>
Gandhinagar Institute of Technology 3161611 AWP
</tr>
<tr>
<td>Name: </td>
<td>{{student.fullName()}}</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<table>
<tr>
<th>Name</th>
<th>Marks</th>
</tr>
<tr ng-repeat = "subject in student.subjects">
<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table>
</td>
</tr>
</table>
</div> </body> </html>
mainApp.js
var mainApp = angular.module("mainApp", []);
studentController.js
mainApp.controller("studentController", function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67}
],
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
Review Questions:
1. Can there be two ng-app for a single angular application?
2. Name a few inbuilt angular filters?
3. What are custom filters? Write down a syntax of the same?
Theory
AngularJS enriches form filling and validation. We can use ng-click event to handle the click
button and use $dirty and $invalid flags to do the validation in a seamless way. Use novalidate
with a form declaration to disable any browser-specific validation. The form controls make
heavy use of AngularJS events. Let us have a look at the events first.
Events
AngularJS provides multiple events associated with the HTML controls. For example, ng-
click directive is generally associated with a button. AngularJS supports the following events
−
ng-click
ng-dbl-click
ng-mousedown
ng-mouseup
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
ng-keydown
ng-keyup
ng-keypress
ng-change
ng-click
Reset data of a form using on-click directive of a button.
Example:
<input name = "firstname" type = "text" ng-model = "firstName" required>
<input name = "lastname" type = "text" ng-model = "lastName" required>
<input name = "email" type = "email" ng-model = "email" required>
<button ng-click = "reset()">Reset</button>
<script>
function studentController($scope) {
$scope.reset = function() {
$scope.firstName = "Mahesh";
$scope.lastName = "Parashar";
$scope.email = "[email protected]";
}
$scope.reset();
}
</script>
Validate Data
The following can be used to track error.
$dirty − states that value has been changed.
$invalid − states that value entered is invalid.
$error − states the exact error.
Example
The following example will showcase all the above-mentioned directives.
testAngularJS.htm
Gandhinagar Institute of Technology 3161611 AWP
<html>
<head>
<title>Angular JS Forms</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px; }
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style> </head> <body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "studentController">
<tr>
Gandhinagar Institute of Technology 3161611 AWP
<td>
<button ng-click = "reset()">Reset</button>
</td>
<td>
<button ng-disabled = "studentForm.firstname.$dirty &&
studentForm.firstname.$invalid || studentForm.lastname.$dirty &&
studentForm.lastname.$invalid || studentForm.email.$dirty &&
studentForm.email.$invalid" ng-click="submit()">Submit</button>
</td>
</tr>
</table>
</form>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.reset = function() {
$scope.firstName = "Mahesh";
$scope.lastName = "Parashar";
$scope.email = "[email protected]";
}
$scope.reset();
});
</script> </body></html>
AngularJS - Includes
HTML does not support embedding HTML pages within the HTML page. To achieve this
functionality, we can use one of the following options −
Using Ajax − Make a server call to get the corresponding HTML page and set it in the
innerHTML of HTML control.
Using Server Side Includes − JSP, PHP and other web side server technologies can
include HTML pages within a dynamic page.
Using AngularJS, we can embed HTML pages within an HTML page using ng-include
directive.
<div ng-app = "" ng-controller = "studentController">
<div ng-include = "'main.htm'"></div>
<div ng-include = "'subjects.htm'"></div>
</div>
$http.get(url).then( function(response) {
$scope.students = response.data;
});
}
</script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script> </body></html>
AngularJS - Views
AngularJS supports Single Page Application via multiple views on a single page. To do this,
AngularJS has provided ng-view and ng-template directives, and $routeProvider services.
ng-view Directive
The ng-view directive simply creates a place holder where a corresponding view (HTML or
ng-template view) can be placed based on the configuration.
Gandhinagar Institute of Technology 3161611 AWP
Usage
Define a div with ng-view within the main module.
<div ng-app = "mainApp">
...
<div ng-view></div>
</div>
ng-template Directive
The ng-template directive is used to create an HTML view using script tag. It
contains id attribute which is used by $routeProvider to map a view with a controller.
Usage
Define a script block with type as ng-template within the main module.
<div ng-app = "mainApp">
...
<script type = "text/ng-template" id = "addStudent.htm">
<h2> Add Student </h2>
{{message}}
</script>
</div>
$routeProvider Service
The $routeProvider is a key service which sets the configuration of URLs, maps them with
the corresponding HTML page or ng-template, and attaches a controller with the same.
Usage 1
Define a script block with type as ng-template within the main module.
<div ng-app = "mainApp">
..
<script type = "text/ng-template" id = "addStudent.htm">
<h2> Add Student </h2>
{{message}}
</script>
</div>
Usage 2
Define a script block with main module and set the routing configuration.
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/addStudent', {
templateUrl: 'addStudent.htm', controller: 'AddStudentController'
})
.when('/viewStudents', {
templateUrl: 'viewStudents.htm', controller: 'ViewStudentsController'
})
.otherwise ({
redirectTo: '/addStudent'
});
}]);
The following points are important to be considered in the above example
$routeProvider is defined as a function under config of mainApp module using key as
'$routeProvider'.
$routeProvider.when defines a URL "/addStudent", which is mapped to
"addStudent.htm". addStudent.htm should be present in the same path as main HTML
Exercise:
1. Write a program for validation using AngularJs Forms.
2. Implement program using AJAX. We have the file data.txt, which will include the
records of the student. An ajax call will be made by the $http service. It is going to
divert & set the response to the students having priority. After this extraction, the tables
will be drawn up in the HTML, which will be based on the students model.
The data.txt file:
[ {
"Name" : "Ronaldo",
"Goals" : 128,
"Ratio" : "69%"
},
{
"Name" : "James",
"Goals" : 007,
"Ratio" : "70%"
},
{
"Name" : "Ali",
"Goals" : 786,
"Ratio" : "99%"
},
{
"Name" : "Lionel ",
"Goals" : 210,
"Ratio" : "100%"
}]
Review Questions:
1. Where should one use form action instead of $http for accessing a method on a
server?
2. Explain the styling form that ngModel adds to CSS classes
Aim:
Theory
AngularJS supports the concept of Separation of Concerns using services architecture.
Services are JavaScript functions, which are responsible to perform only specific tasks. This
makes them individual entities which are maintainable and testable. The controllers and filters
can call them on requirement basis. Services are normally injected using the dependency
injection mechanism of AngularJS.
AngularJS provides many inbuilt services. For example, $http, $route, $window, $location,
etc. Each service is responsible for a specific task such as the $http is used to make ajax call
to get the server data, the $route is used to define the routing information, and so on. The
inbuilt services are always prefixed with $ symbol.
There are two ways to create a service −
Factory
Service
Using Factory Method
In this method, we first define a factory and then assign method to it.
var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
Using Service Method
In this method, we define a service and then assign method to it. We also inject an already
available service to it.
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
Example:
The following example shows use of all the above mentioned directives −
testAngularJS.htm
<html>
<head>
<title>Angular JS Services</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
mainApp.controller('CalcController', function($scope, CalcService) {
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
</script>
</body>
</html>
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
Factory
Factory is a function which is used to return value. It creates a value on demand whenever a
service or a controller requires it. It generally uses a factory function to calculate and return
the value.
//define a module
var mainApp = angular.module("mainApp", []);
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
//inject the factory "MathService" in a service to utilize the multiply method of factory.
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
Service
Service is a singleton JavaScript object containing a set of functions to perform certain tasks.
Service is defined using service() function and it is then injected into the controllers.
//define a module
var mainApp = angular.module("mainApp", []);
...
//create a service which defines a method square to return square of a number.
mainApp.service('CalcService', function(MathService) {
Gandhinagar Institute of Technology 3161611 AWP
this.square = function(a) {
return MathService.multiply(a,a);
}
});
//inject the service "CalcService" into the controller
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
Provider
Provider is used by AngularJS internally to create services, factory, etc. during the config
phase. The following script can be used to create MathService that we created earlier. Provider
is a special factory method with get() method which is used to return the value/service/factory.
//define a module
var mainApp = angular.module("mainApp", []);
...
//create a service using provider which defines a method square to return square of a number.
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
Constant
Constants are used to pass values at the config phase considering the fact that value cannot be
used during the config phase.
mainApp.constant("configParam", "constant value");
Example:
The following example shows the use of all the above-mentioned directives −
testAngularJS.htm
<html>
<head>
<title>AngularJS Dependency Injection</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "CalcController">
<p>Enter a number: <input type = "number" ng-model = "number" /></p>
<button ng-click = "square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
mainApp.value("defaultInput", 5);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
</script>
</body>
</html>
Review Questions:
Theory
Node.js is a very powerful JavaScript-based platform built on Google Chrome's JavaScript V8
Engine. It is used to develop I/O intensive web applications like video streaming sites, single-
page applications, and other web applications. Node.js is open source, completely free, and
used by thousands of developers around the world.
What is Node.js?
Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine).
Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36. The definition
of Node.js as supplied by its official documentation is as follows −
o Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and
scalable network applications. Node.js uses an event-driven, non-blocking I/O model
that makes it lightweight and efficient, perfect for data-intensive real-time applications
that run across distributed devices.
o Node.js is an open source, cross-platform runtime environment for developing server-
side and networking applications. Node.js applications are written in JavaScript, and
can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux.
o Node.js also provides a rich library of various JavaScript modules which simplifies the
development of web applications using Node.js to a great extent.
o Node.js = Runtime Environment + JavaScript Library
Features of Node.js
Following are some of the important features that make Node.js the first choice of software
architects.
o Asynchronous and Event Driven − All APIs of Node.js library are asynchronous,
that is, non-blocking. It essentially means a Node.js based server never waits for an
API to return data. The server moves to the next API after calling it and a notification
mechanism of Events of Node.js helps the server to get a response from the previous
API call.
o Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is
very fast in code execution.
o Single Threaded but Highly Scalable − Node.js uses a single threaded model with
event looping. Event mechanism helps the server to respond in a non-blocking way and
makes the server highly scalable as opposed to traditional servers which create limited
threads to handle requests. Node.js uses a single threaded program and the same
program can provide service to a much larger number of requests than traditional
servers like Apache HTTP Server.
o No Buffering − Node.js applications never buffer any data. These applications simply
output the data in chunks.
o License − Node.js is released under the MIT license.
Who Uses Node.js?
Following is the link on github wiki containing an exhaustive list of projects, application and
companies which are using Node.js. This list includes eBay, General Electric, GoDaddy,
Microsoft, PayPal, Uber, Wikipins, Yahoo!, and Yammer to name a few.
For most of the examples given in this tutorial, you will find a Try it option, so just make use
of it and enjoy your learning.
Local Environment Setup
If you are still willing to set up your environment for Node.js, you need the following two
softwares available on your computer, (a) Text Editor and (b) The Node.js binary installables.
Gandhinagar Institute of Technology 3161611 AWP
Text Editor
This will be used to type your program. Examples of few editors include Windows Notepad,
OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of text editor can vary on different operating systems. For example,
Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or
UNIX.
The files you create with your editor are called source files and contain program source code.
The source files for Node.js programs are typically named with the extension ".js".
Before starting your programming, make sure you have one text editor in place and you have
enough experience to write a computer program, save it in a file, and finally execute it.
The Node.js Runtime
The source code written in source file is simply javascript. The Node.js interpreter will be
used to interpret and execute your javascript code.
Node.js distribution comes as a binary installable for SunOS , Linux, Mac OS X, and Windows
operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures.
Following section guides you on how to install Node.js binary distribution on various OS.
Download Node.js archive
Download latest version of Node.js installable archive file from Node.js Downloads. At the
time of writing this tutorial, following are the versions available on different OS.
Table 1: Node.js versions available on different OS
OS Archive name
Windows node-v6.3.1-x64.msi
Linux node-v6.3.1-linux-x86.tar.gz
Mac node-v6.3.1-darwin-x86.tar.gz
SunOS node-v6.3.1-sunos-x86.tar.gz
Congratulations, you have your first HTTP server up and running which is responding to all
the HTTP requests at port 8081.
REPL Terminal
REPL stands for Read Eval Print Loop and it represents a computer environment like a
Windows console or Unix/Linux shell where a command is entered and the system responds
with an output in an interactive mode. Node.js or Node comes bundled with a REPL
environment. It performs the following tasks −
o Read − Reads user's input, parses the input into JavaScript data-structure, and stores
in memory.
o Eval − Takes and evaluates the data structure.
o Print − Prints the result.
o Loop − Loops the above command until the user presses ctrl-c twice.
The REPL feature of Node is very useful in experimenting with Node.js codes and to debug
JavaScript codes.
Callbacks
What is Callback?
Callback is an asynchronous equivalent for a function. A callback function is called at the
completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are
written in such a way that they support callbacks.
For example, a function to read a file may start reading file and return the control to the
execution environment immediately so that the next instruction can be executed. Once file I/O
is complete, it will call the callback function while passing the callback function, the content
of the file as a parameter. So there is no blocking or wait for File I/O. This makes Node.js
highly scalable, as it can process a high number of requests without waiting for any function
to return results.
Blocking Code Example
Create a text file named input.txt with the following content −
Tutorials Point is giving self learning content
Gandhinagar Institute of Technology 3161611 AWP
to teach the world in simple and easy way!!!!!
Create a js file named main.js with the following code −
var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
Now run the main.js to see the result −
$ node main.js
Verify the Output.
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Program Ended
Non-Blocking Code Example
Create a text file named input.txt with the following content.
GIT is best college in Gujarat,
to teach the world in simple and easy way!!!!!
Update main.js to have the following code −
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");
Now run the main.js to see the result −
$ node main.js
Verify the Output.
Program Ended
GIT is best college in Gujarat,to teach the world in simple and easy way!!!!!
These two examples explain the concept of blocking and non-blocking calls.
The first example shows that the program blocks until it reads the file and then only it
proceeds to end the program.
The second example shows that the program does not wait for file reading and proceeds
to print "Program Ended" and at the same time, the program without blocking
continues reading the file.
Thus, a blocking program executes very much in sequence. From the programming point of
view, it is easier to implement the logic but non-blocking programs do not execute in
sequence. In case a program needs to use any data to be processed, it should be kept within
the same block to make it sequential execution.
Exercise:
1. Create a Calculator Node.js Module with functions add, subtract and multiply. And
use the Calculator module in another Node.js file.
2. Create a file with data provided and read, write and delete data
Review Questions:
1. Why is Node.js preferred over other backend technologies like Java and PHP?
2. What is an EventEmitter in Node.js?
3. How would you use a URL module in Node.js?
Theory
Database
Database is a physical container for collections. Each database gets its own set of files on the
file system. A single MongoDB server typically has multiple databases.
Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A
collection exists within a single database. Collections do not enforce a schema. Documents
within a collection can have different fields. Typically, all documents in a collection are of
similar or related purpose.
Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema
means that documents in the same collection do not need to have the same set of fields or
structure, and common fields in a collection's documents may hold different types of data.
Table 1: Relationship of RDBMS terminology with MongoDB.
RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
column Field
mysqld/Oracle mongod
mysql/sqlplus mongo
Any relational database has a typical schema design that shows number of tables and the
relationship between these tables. While in MongoDB, there is no concept of relationship.
Advantages of MongoDB over RDBMS
o Schema less − MongoDB is a document database in which one collection holds
different documents. Number of fields, content and size of the document can differ
from one document to another.
Gandhinagar Institute of Technology 3161611 AWP
o Structure of a single object is clear.
o No complex joins.
o Deep query-ability. MongoDB supports dynamic queries on documents using a
document-based query language that's nearly as powerful as SQL.
o Tuning.
o Ease of scale-out − MongoDB is easy to scale.
o Conversion/mapping of application objects to database objects not needed.
o Uses internal memory for storing the (windowed) working set, enabling faster access
of data.
Why Use MongoDB?
o Document Oriented Storage − Data is stored in the form of JSON style documents.
o Index on any attribute
o Replication and high availability
o Auto-Sharding
o Rich queries
o Fast in-place updates
o Professional support by MongoDB
Where to Use MongoDB?
o Big Data
o Content Management and Delivery
o Mobile and Social Infrastructure
o User Data Management
o Data Hub
Install MongoDB On Windows
To install MongoDB on Windows, first download the latest release of MongoDB
from https://www.mongodb.com/download-center.
Now install the downloaded file, by default, it will be installed in the folder C:\Program
Files\.
MongoDB requires a data folder to store its files. The default location for the MongoDB data
directory is c:\data\db. So you need to create this folder using the Command Prompt. Execute
the following command sequence.
C:\>md data
C:\md data\db
Then you need to specify set the dbpath to the created directory in mongod.exe. For the same,
issue the following commands.
In the command prompt, navigate to the bin directory current in the MongoDB installation
folder.
Suppose my installation folder is C:\Program Files\MongoDB
C:\Users\XYZ>d:cd C:\Program Files\MongoDB\Server\4.2\bin
C:\Program Files\MongoDB\Server\4.2\bin>mongod.exe --dbpath "C:\data"
This will show waiting for connections message on the console output, which indicates that
the mongod.exe process is running successfully.
Now to run the MongoDB, you need to open another command prompt and issue the following
command.
C:\Program Files\MongoDB\Server\4.2\bin>mongo.exe
MongoDB shell version v4.2.1
connecting to:
mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("4260beda-f662-4cbe-9bc7-5c1f2242663c") }
MongoDB server version: 4.2.1
>
This will show that MongoDB is installed and run successfully. Next time when you run
MongoDB, you need to issue only commands.
Create Database
The use Command
MongoDB use DATABASE_NAME is used to create database. The command will create a
new database if it doesn't exist, otherwise it will return the existing database.
Syntax
Basic syntax of use DATABASE statement is as follows −
use DATABASE_NAME
Example:
If you want to use a database with name <mydb>, then use DATABASE statement would be
as follows −
>use mydb
switched to db mydb
Review Questions:
1. How do we implement async in Node.js?
2. How would you connect a MongoDB database to Node.js