0% found this document useful (0 votes)
11 views93 pages

UNIT-1 (Introduction To Full Stack Development)

This document provides an introduction to full stack development, covering both front end and back end components, including technologies like Node.js, MongoDB, Express, and Angular. It explains the roles of users, browsers, web servers, and backend services in web applications, detailing how they interact and function together. Additionally, it discusses the importance of various programming languages and frameworks used in full stack development, emphasizing the significance of responsive design and performance.

Uploaded by

vasanthi.kota17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views93 pages

UNIT-1 (Introduction To Full Stack Development)

This document provides an introduction to full stack development, covering both front end and back end components, including technologies like Node.js, MongoDB, Express, and Angular. It explains the roles of users, browsers, web servers, and backend services in web applications, detailing how they interact and function together. Additionally, it discusses the importance of various programming languages and frameworks used in full stack development, emphasizing the significance of responsive design and performance.

Uploaded by

vasanthi.kota17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

UNIT-1 (Introduction to full stack development)

• Introduction to Full Stack Development: Understanding the Basic


Web Development Framework- User, Browser, Webserver,
Backend Services, Full Stack Components - Node.js, MongoDB,
Express, React, Angular. Java Script Fundamentals, NodeJS-
Understanding Node.js, Installing Node.js, Working with Node
Packages, creating a Node.js Application, Understanding the
Node.js Event Model, Adding Work to the Event Queue,
Implementing Callbacks
FULL STACK DEVELOPMENT
•It is the process of building both the front end and back end of
an application.

•Front end
•Back end
•Data bases
FULL STACK DEVELOPMENT
•A web-application is an application program that is usually stored on a remote server, and
users can access it through the use of Software known as web-browser.

•It is a type of computer program that usually runs with the help of a web browser and also
uses many web technologies to perform various tasks on the internet.

•A web application can be developed for several uses, which can be used by anyone like it can
be used as an individual or as a whole organization for several reasons.

•Frontend and Backend are key terms in web development.

•The frontend is what users see and interact with, while the backend is how everything
works behind the scenes. Both sides need to work together seamlessly to ensure a functional
website.
1. Front End Development
•The frontend is the part of the website users directly interact with. This includes the design,
menus, text, images, videos, and overall layout.

•The main languages used for frontend development are HTML, CSS, and JavaScript.
Responsiveness and performance are the two main objectives of the Front End.

•The developer must ensure that the site is responsive i.e. it appears correc tly on devices of
all sizes no part of the website should behave abnormally irrespective of the size of the screen.
Front End Languages
∙ HTML: HTML stands for Hypertext Markup Language. It is used to design the front-end portion of
web pages using a markup language. HTML is a combination of Hypertext and Markup language.
Hypertext defines the link between web pages..

∙ CSS: Cascading Style Sheets fondly referred to as CSS is a simply designed language intended to
simplify the process of making web pages presentable. CSS allows you to apply styles to web pages.

∙ JavaScript: JavaScript is a famous scripting language used to create magic on sites to make the site
interactive for the user. It is used to enhance the functionality of a website to run cool games and
web-based software. Applicable in both front-end and back-end, Javascript is key to becoming a
good developer.

•There are many other languages through which one can do front-end development depending upon
the framework for example Flutter uses Dart, React uses JavaScript and Django uses Python…
Frontend Frameworks and Libraries:
∙ AngularJS: unit-4

∙ React.js: unit -5

∙ jQuery:

∙ SASS:

∙ Flutter:
2. Back End Development
• The backend is the server side of the website.

• It manages data and ensures everything on the frontend works properly.

• Users don’t see or interact directly with the backend; it’s the behind-the-scenes functionality.

• The parts and characteristics developed by backend designers are indirectly accessed by
users through a front-end application.

• Activities, like writing APIs, creating libraries, and working with system components
without user interfaces or even systems of scientific programming, are also included in the
backend.

Back End Languages
PHP: PHP is a server-side scripting language designed specifically for web development. Since PHP
code is executed on the server side, it is called a server-side scripting language.

∙ Java: Java is one of the most popular and widely used programming languages and platforms. It is
highly scalable.

∙ Python: Python is a programming language that lets you work quickly and integrate systems more
efficiently.

• Node.js: Node.js is an open-source and cross-platform runtime environment for executing JavaScript
code outside a browser. NodeJS is not a framework, and it’s not a programming language. We often
use Node.js for building back-end services like APIs like Web App or Mobile App.
Back-End Frameworks
∙ Express : unit-4

∙ Django

∙ Ruby on Rails

∙ Laravel

∙ Spring

∙ Some more back-end programming/scripting languages are C#, Ruby, GO, etc.
Understanding the Basic Web Development Framework
• The main components of any given web framework are the user, browser, webserver, and
backend services.
• Although websites vary greatly on appearance and behavior, all have these basic components in
one form or another.
• The components are described in a top-down manner from user down to backend services.
User
• Users are a fundamental part of all websites; User expectations define the
requirements for developing a good website, and these expectations have changed a
lot over the years.
• Users expect websites to behave closer to applications installed on their computers
and mobile devices.
• The user role in a web framework is to sit on the visual output and interaction input
of webpages.
• Users view the results of the web framework processing and then provide
interactions using mouse clicks, keyboard input, and swipes and taps on mobile
devices.
Browser
• The browser plays three roles in the web framework.

1. It provides communication to and from the webserver.

2. It interprets the data from the server and renders it into the view that the
user actually sees.

3. The browser handles user interaction through the keyboard, mouse,


touchscreen, or other input device and takes the appropriate action.
Browser
1. Browser to Webserver Communication
• It consists of a series of requests using the HTTP and HTTPS protocols.
• Hypertext Transfer Protocol (HTTP) defines communication between the
browser and the webserver.
• It also defines what types of requests can be made as well as the format of
those requests and the HTTP response.

•HTTPS adds an additional security layer, SSL/TLS, to ensure secure


connections by requiring the webserver to provide a certificate to the browser. The
user then can determine whether to accept the certificate before allowing the
connection.
Browser
• The browser makes three main types of requests to the server:
■ GET: The GET request is typically used to retrieve data from the server, such as .html files,
images, or JSON data.
■ POST: POST requests are used when sending data to the server, such as adding an item to a
shopping cart or submitting a web form.
■ AJAX: Asynchronous JavaScript and XML (AJAX) is actually just a GET or POST request
done directly by JavaScript running in the browser. Despite the name, an AJAX request can
receive XML, JSON, or raw data in the response. Entire web pages do not have to reloaded
each time data is needed from the server.
2. Rendering the Browser View
• The screen that the user actually views and interacts with is often made up of several different
pieces of data retrieved from the webserver.
• The browser reads data from the initial URL and then renders the HTML document to build a
Document Object Model (DOM).
• The DOM is a tree structure object with the HTML document as the root. The structure of the
tree basically matches the structure of the HTML document. For example, the document will have
html as a child, and html will have head and body as children, and body may have div, p, or other
elements as children, like this:
•document
•+ html
•+ head
•+ body
•+ div
•+ p
• The browser interprets each DOM element and renders it to the user’s screen to build the
webpage view..
2. Rendering the Browser View
2. Rendering the Browser View
The following are the most common types of data the browser uses to render the final user view as
well as define the webpage behavior.
■ HTML files: These provide the fundamental structure of the DOM.
■ CSS files: These define how each of the elements on the page is to be styled; for example, font, color,
orders, and spacing.
■ Client-side scripts: These are typically JavaScript files. They can provide added functionality to the
webpage, manipulate the DOM to change the look of the webpage, and provide any necessary logic
required to display the page and provide functionality.
■ Media files: Image, video, and sound files are rendered as part of the webpage.
■ Data: Any data, such as XML, JSON, or raw text, can be provided by the webserver as a response to an
AJAX request.
■ HTTP headers: The HTTP protocol defines a set of headers that can be used by the browser and client-side
scripts to define the behavior of the webpage. The HTTP headers also define the type of data in the request
as well as the type of data expected to be returned back to the browser.
3. User Interaction
• The user interacts with the browser via input devices such as mouse,
keyboards, and touchscreens.
• The browser has an elaborate event system that captures these user input
events and then takes the appropriate action.
• Actions vary from displaying a popup menu to loading a new document
from the server to executing client-side JavaScript.
Webserver

• The webserver’s main focus is handling requests from browsers.


• The browser may request a document, post data, or perform an AJAX request to get a
data.
• The webserver uses the HTTP headers as well as the URL to determine what action to
take.
• This is where things get different depending on the webserver, configuration, and
technologies used.

Webservers, such as Apache and IIS, are made to serve static files such as .html, .css, and
media files. To handle POST requests that modify server data and AJAX requests to interact
with backend services, webservers need to be extended with server-side scripts.
Server-side program & Backend Services
• A server-side program is really anything that can be executed by the webserver to perform the task the
browser is requesting. These can be written in PHP, Python, C, C++, C#, Java, …. Webservers such as
Apache and IIS provide mechanisms to include server-side scripts and then wire them up to specific URL
locations requested by the browser.
• The server-side scripts either generate the response directly by executing their code or connect with other
backend servers such as databases to obtain the necessary information and then use that information to build
and send the appropriate response.
• Backend Services
• Backend services are services that run behind the webserver and provide data used to build responses to
the browser.
• The most common type of backend service is a database that stores information.
• When a request comes in from the browser that requires information from the database or other backend
service, the server-side script connects to the database, retrieves the information, formats it, and then sends it
back to the browser. Conversely, when data comes in from a web request that needs to be stored in the
database, the server-side script connects to the database and updates the data.
Understanding the Node.js-to-Angular Stack Components
Figure 1.2 provides a basic diagram of how the Node.js-to-Angular stack fits into the basic
website/web application model.
Understanding the Node.js-to-Angular Stack Components
• The most common—and we believe the best—version of this stack is the Node.js-to-Angular
stack comprised of MongoDB, Express, Angular, and Node.js.
In the Node.js-to-Angular stack:
• Node.js provides the fundamental platform for development. The backend services and
server-side scripts are all written in Node.js.
• MongoDB provides the data store for the website but is accessed via a MongoDB driver
Node.js module.
• The webserver is defined by Express, which is also a Node.js module.
• The view in the browser is defined and controlled using the Angular framework or React.
• Angular is an MVC framework where the model is made up of JSON or JavaScript objects, the
view is HTML/ CSS, and the controller is made up of Angular JavaScript.
Browsers and Javascript engine
Node.js
• Node.js is a development framework based on Google’s V8 JavaScript engine.
Therefore, Node.js code is written in JavaScript and then compiled into machine code
by V8 to be executed.
• Many of your backend services can be written in Node.js, as can the server-side
scripts and any supporting web application functionality.
• The nice thing about Node.js is that it is all just JavaScript, so you can easily take
functionality from a client-side script and place it in a server-side script.
• Also, the webserver can run directly within the Node.js platform as a Node.js
module, so it makes it much easier than, say, Apache at wiring up new services or
server-side scripts.
Node.js
• The following are just a few reasons why Node.js is a great framework to start from:
JavaScript end-to-end: One of the biggest advantages to Node.js is that it allows you to write both
server- and client-side scripts in JavaScript. With Node.js you can take JavaScript written on
the client and easily adapt it for the server and vice versa.
Event-driven scalability: Node.js applies a different logic to handling web requests. Rather than
having multiple threads waiting to process web requests, they are processed on the same thread using
a basic event model. This allows Node.js webservers to scale in ways that traditional webservers never
can.
Extensibility: Node.js has a great following and an active development community. New modules
to extend Node.js functionality are being developed all the time. Also it is simple to install and include
new modules in Node.js, making it easy to extend a Node.js project to include new functionality in
minutes.
Time: Node.js is super easy to set up and develop in. In only a few minutes, you can install Node.js
and have a working webserver.
MongoDB
• MongoDB is an agile and scalable NoSQL (Not Only SQL) database.
• The name Mongo comes from “humongous.”
• It is based on the NoSQL document store model, meaning that data is stored in the
database as a form of JSON objects rather than the traditional columns and rows of a
relational database.
• MongoDB provides great website backend storage for high traffic websites that need to
store data such as user comments, blogs, or other items because it is fast, scalable, and easy
to implement.
• Node.js supports a variety of DB access drivers, so the data store could just as easily be
MySQL or some other database.
MongoDB
• However, the following are some of the reasons that MongoDB really fits in the Node.js stack well:
■ Document orientation: Because MongoDB is document-oriented, the data is stored in the
database in a format close to what you will be dealing with in both server-side and client- side
scripts. This eliminates the need to transfer data from rows to objects and back.
High performance: MongoDB is one of the highest performing databases available. Especially
today when more and more people interact with websites, it is important to have a backend that can
support heavy traffic.
High availability: MongoDB’s replication model makes it easy to maintain scalability while
keeping high performance.
High scalability: MongoDB’s structure makes it easy to scale horizontally by sharing the data
across multiple servers.
No SQL injection: MongoDB is not susceptible to SQL injection (putting SQL statements in web
forms or other input from the browser that compromises the DB security) because objects are
stored as objects, not using SQL strings.
Express
• The Express module acts as the webserver in the Node.js-to-Angular stack.
• The Express module extends Node.js to provide several key components for handling web
requests.
The following is a partial list of the valuable features of Express:
■ Route management: Express makes it easy to define routes (URL endpoints) that tie directly
to Node.js script functionality on the server.
■ Error handling: Express provides built-in error handling for documents not found and other
errors.
■ Easy integration: An Express server can easily be implemented behind an existing reverse proxy
system such as Nginx or Varnish. This allows it to be easily integrated into your existing secured
system.
■ Cookies: Express provides easy cookie management.
■ Session and cache management: Express also enables session management and cache
management.
Angular
• Angular is a client-side framework developed by Google.
• Angular provides all the functionality needed to handle user input in the browser, manipulate data on
the client side, and control how elements are displayed in the browser view.
• It is written using TypeScript.
• Angular provides a framework that makes it easy to implement web applications using the MVC framework.
• Benefits of Angular:
■ Data binding: Angular has a clean method to bind data to HTML elements using its powerful scope
mechanism.
■ Extensibility: The Angular architecture allows you to easily extend almost every aspect of the language to
provide your own custom implementations.
■ Clean: Angular forces you to write clean, logical code.
■ Reusable code: The combination of extensibility and clean code makes it easy to write reusable code in
Angular. Support: Google is investing a lot into this project, which gives it an advantage over other similar
initiatives.
■ Compatibility: Angular is based on TypeScript, which makes it easier to begin integrating Angular into your
environment and to reuse pieces of your existing code within the structure of the Angular framework
ReactJS
• ReactJS, also known as React, is a popular JavaScript library for building user interfaces.
• It is also referred to as a front-end JavaScript library.
• It was developed by Facebook and is widely used for creating dynamic and interactive web applications.
• React is a declarative, component based library that allows developers to build reusable UI components and It
follows the Virtual DOM (Document Object Model) approach, which optimizes rendering performance by
minimizing DOM updates.
Features of React:
1. Component-Based Architecture
2. JSX (JavaScript Syntax Extension)
3. Virtual DOM
4. One-way Data Binding
5. Performance
6. Components
7. Single-Page Applications (SPAs)
JavaScript Primer(basics)
Each component of Node.js, Express, TypeScript, and Angular is based on the JavaScript
language. This makes it easy to implement and reuse code at all levels of your web development
stack. we need to familiarize you with some of the language basics of JavaScript, such as variables,
functions, and objects.
• Defining Variables
• Variables are a means to name data so that you can use that name to temporarily store and access
data from your JavaScript files.
• Variables can point to simple data types such as numbers or strings, or they can point to more
complex data types such as objects.
•To define a variable in JavaScript you use the var keyword and then give the variable a name, for
example:
• var myData;
• You can also assign a value to the variable in the same line.
• var myString = "Some Text";
JavaScript Primer(basics)
• The following lines work as well:
• var myString;
• myString = "Some Text";

• Once you have declared the variable, you can use the name to assign the variable a value and
access the value of the variable:
• var myString = "Some Text";
• var newString = myString + " Some More Text";
• Your variable names should describe the data stored in them so that it is easy to use them later in
your program.
• The only rules for creating variable names is that they must begin with a letter, $, or _, and they
cannot contain spaces. Also remember that variable names are case sensitive, so using myString is
different from MyString.
Understanding JavaScript Data Types
•JavaScript has 8 Datatypes
•String
•Number
•Bigint
•Boolean
•Undefined
•Null
•Symbol
•Object
Understanding JavaScript Data Types
• JavaScript uses data types to determine how to handle data assigned to a variable. The variable type
determines what operations you can perform on the variable, such as looping or executing.
■ String: Stores character data as a string. The character data is specified by either single or double
quotes. All the data contained in the quotes will be assigned to the string variable. For example:
• var myString = 'Some Text';
• var anotherString = 'Some More Text';
■ Number: Stores the data as a numerical value. Numbers are useful in counting, calculations,
and comparisons. Some examples are
• var myInteger = 1;
• var cost = 1.33;

■ Boolean: Stores a single bit that is either true or false. Booleans are often used for flags. The
following examples define a true and a false variable.
• var yes = true;
• var no = false;
Understanding JavaScript Data Types
■ Array: An indexed array is a series of separate distinct data items all stored under a single variable
name. Items in the array can be accessed by their zero-based index using array[index].
• var arr = ["one", "two", "three"] ;
• var first = arr[0];
•Object literal:
JavaScript supports the ability to create and use object literals. When you use an object literal you
can access values and functions in the object using the object.property syntax.
• var obj = {"name": "Brendan", "Hobbies":["Video Games", "camping"], "age”:22};
• var name = obj.name;

■ Null: At times you do not have a value to store in a variable either because it hasn’t been created
or you are no longer using it. At this time you can set a variable to null.
• var newVar = null;
Java Script Operators :
• Assignment operators
• Comparison operators
• Arithmetic operators
• Bitwise operators
• Logical operators
• BigInt operators
• String operators
• Conditional (ternary) operator
• Comma operator
• Unary operators
• Relational operators
Using if Statements
•An if statement allows you to separate code execution based on the evaluation of a
comparison. In the following lines of code the conditional operators are in (), and the code to
execute if the conditional evaluates to true is in {}:
if(x==5){ do_something();
}
• In addition to only executing code within the if statement block, you can specify an else
• block that gets executed only if the condition is false. For example:
if(x==5){ do_something();
} else { do_something_else();
}
•You can also chain if statements together. To do this add a conditional statement along with an
else statement, for example:
if(x<5){ do_something();
} else if(x<10) { do_something_else();
} else { do_nothing();
Implementing switch Statements
•The switch statement allows you to evaluate an expression once and then, based on the
value, execute one of many different sections of code.
• The syntax for the switch statement is
switch(expression){
case value1:
<code to execute>
break;
case value2:
<code to execute>
break;
default:
<code to execute if not value1 or value2>
}
Implementing Looping
• while Loops
• The most basic type of looping in JavaScript is the while loop. A while loop tests an expression and
continues to execute the code contained in its {} brackets until the expression evaluates to false.
while (i<5){
console.log("Iteration " + i + "<br>"); i++;
}
• do/while Loops
•Another type of while loop is the do/while loop. This is useful if you always want to execute the code
in the loop at least once and the expression cannot be tested until the code has executed at least once.
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
var i=0;
do{
var day=days[i++];
console.log("It's " + day + "<br>");
} while (day != "Wednesday");
for Loops
• The JavaScript for loop allows you to execute code a specific number of times by using a for
statement that combines three statements into a single block of execution using the following
syntax:
for (assignment; condition; update;){
code to be executed;
}
• The for statement uses those three statements as follows when executing the loop:
■ assignment: Executed before the loop begins and not again. This is used to initialize
variables that will be used in the loop as conditionals.
■ condition: Expression evaluated before each iteration of the loop. If the expression evaluates
to true the loop is executed; otherwise, the for loop execution ends.
■ update: Executed each iteration after the code in the loop has executed. This is typically used
to increment a counter that is used in statement 2.
Creating Functions
Syntax for Function Declaration:
function functionName(x, y) { statements... return (z) };

Syntax for Function Expression (anonymous):


let variableName = function(x, y) { statements... return (z) };

Syntax for Function Expression (named):


let variableName = function functionName(x, y) { statements... return (z) };

Syntax for Arrow Function:


let variableName = (x, y) => { statements... return (z) };
Creating Functions

Syntax for Function Declaration:


function callAdd(x, y) {
let z = x + y;
return z;
}
console.log("Addition : " + callAdd(7, 4));
Creating Functions
Code for Function Expression (anonymous)

let calSub = function (x, y) {

let z = x - y;

return z;

console.log("Subtraction : " + calSub(7, 4));


Creating Functions
Code for Function Expression (named)

let calMul = function Mul(x, y) {


let z = x * y;
return z;
}

console.log("Multiplication : " + calMul(7, 4));


Creating Functions
Code for Arrow Function

let calDiv = (x, y) => {


let z = x / y;
return z;
}
console.log("Division : " + calDiv(24, 4));
Creating Functions
• One of the most important parts of JavaScript is making code that is reusable by other code. A
function is a series of code statements combined together in a single block and given a name.
The code in the block can then be executed by referencing that name.
Defining Functions
• Functions are defined using the function keyword followed by a name that describes the use of
the function, a list of zero or more arguments in (), and a block of one or more code state- ments
in {}.
function myFunction(){ console.log("Hello World");
}
• To execute the code in myFunction(), all you need to do is add the following line to the main
JavaScript or inside another function.
• myFunction();
Creating Functions
• Passing Variables to Functions
• Frequently you need to pass specific values to functions that they will use when executing their code.
Values are passed in comma-delimited form to the function. The function definition needs a list of variable
names in () that match the number being passed in.
function greeting(name, city)
{ console.log("Hello " + name);
console.log(". How is the weather in " + city);
}
•To call the greeting() function, you need to pass in a name value and a city value. The value can be a
direct value or a previously defined variable. To illustrate this, the following code executes the
greeting() function with a name variable and a direct string for the city:
• var name = "Brad";
• greeting(name, "Florence");
Creating Functions
• Returning Values from Functions
•Adding a return keyword followed by a variable or value returns that value from the function.
For example, the following code calls a function to format a string, assigns the value returned
from the function to a variable, and then writes the value to the console:
•function formatGreeting(name, city)
{ var retStr = "";
retStr += "Hello <b>" + name +"<b>,<br>);
retStr += "Welcome to " + city + "!";
return retStr;
}
• var greeting = formatGreeting("Brad", "Rome"); console.log(greeting);
• When the function encounters a return statement, code execution of the function is stopped
immediately. If the return statement contains a value to return, then that value is returned.
Using JavaScript Objects
• JavaScript has several built-in objects such as Number, Array, String, Date, and Math. Each of
these built-in objects has member properties and methods.
• JavaScript provides a nice object-oriented programming structure for you to create your own
custom objects. Using objects rather than just a collection of functions is key to writing clean,
efficient, reusable JavaScript code.
• Using Object Syntax
• An object is really just a container to group multiple values and, in some instances, functions
together. The values of an object are called properties, and functions are called methods.
• To use a JavaScript object, you must first create an instance of the object
• . Object instances are created using the new keyword with the object constructor name.
Using JavaScript Objects
• For example, to create a number object, you use the following line of code to create an
instance of the built-in Number object in JavaScript:
• var x = new Number ("5");
• Object syntax is straightforward: You use the object name, followed by a dot, and then the
property or method name.
• var s = myObj.name;
• myObj.name = "New Name";
• var name = myObj.getName();
• myObj.getName = function() { return this.name; };
•You can also create objects and assign variables and functions directly using {} syntax.
var obj = {
name: "My Object",
value: 7,
getValue: function() { return this.value; }
};
Using JavaScript Objects
• // 1.Create an Object
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
• //2. Create an Object // 3.Create an Object
const person = new Object();
const person = {};
// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
java script - Embedding code
<!DOCTYPE html >
<html>
<head>
<title> Embedding code </title>
<script>
document.write("Welcome to Java Script and HTML");
</script>
</head>
<body>
<p>Inthis example we saw how to add JavaScript in the head section </p>
</body>
</html>
java script -inline
</head>
<body>
<p>
<a href="#" onClick="alert('Welcome to java scripts and HTML!');">
Click Me
</a>
</p>
<p> in this example we saw how to use inline JavaScript or directly in an HTML
tag. </p>
</body>
</html>
java script – external file
<html>
<head>
<meta charset="utf-8">
<title>Including a External JavaScript File</title> function display(){
</head> alert("Welcome to java
scripts and HTML....");
<body>
}
<form>
<input type="button" value="Result"
onclick="display()"/>
</form>
<script src="display.js">
</script>
</body>
</html>
Getting Started with Node.js
• Node.js is a website/application framework designed with high scalability in mind.
• It was designed to take advantage of the existing JavaScript technology in the
browser and flow those same concepts all the way down through the webserver into
the backend services.
• Node.js is a great technology that is easy to implement and yet extremely scalable.
• Node.js is a modular platform, meaning that much of the functionality is provided by
external modules rather than being built in to the platform.
• The Node.js culture is active in creating and publishing modules for almost every
imaginable need.
• Therefore, we need to focus on understanding and using the Node.js tools to build,
publish, and use your own Node.js modules in applications.
Getting Started with Node.js
• Understanding Node.js
• Node.js was developed in 2009 by Ryan Dahl.
• Google had just come out with the V8 JavaScript engine for the Chrome web browser,
which was highly optimized for web traffic.
• Dahl created Node.js on top of V8 as a server-side environment that matched the client-side
environment in the browser.
• The result is an extremely scalable server-side environment that allows developers to more
easily bridge the gap between client and server.
• The fact that Node.js is written in JavaScript allows developers to easily navigate back and
forth between client and server code and even reuse code between the two environments.
• Node.js has a great ecosystem with new extensions being written all the time.
• The Node.js environment is clean and easy to install, configure, and deploy.
Who Uses Node.js?
• Node.js quickly gained popularity among a wide variety of companies. The following are
just a few of the companies using the Node.js technology:
■ Yahoo! , LinkedIn, eBay, New York Times, Dow Jones, Microsoft etc.

Applications of Node.js :
Web applications
Internet of Things systems
APIs
Real-time chats
Complex single-page applications
Real-time collaboration tools
Streaming apps
What Is Node.js Used For?
• Node.js can be used for a wide variety of purposes. Because it is based on V8 and
has highly optimized code to handle HTTP traffic, the most common use is as a
webserver. However, Node.js can also be used for a variety of other web services
such as:
■ Web services APIs such as REST
■ Real-time multiplayer games
■ Backend web services such as cross-domain, server-side requests
■ Web-based applications
■ Multiclient communication such as IM
What Does Node.js Come With?
• Node.js comes with many built-in modules available right out of the box.
■ Assertion testing: Allows you to test functionality within your code.
■ Buffer: Enables interaction with TCP streams and file system operations.
■ C/C++ add-ons: Allows for C or C++ code to be used just like any other Node.js module.
■ Child processes: Allows you to create child processes.
■ Cluster: Enables the use of multicore systems.
■ Command line options: Gives you Node.js commands to use from a terminal.
■ Console: Gives the user a debugging console.
■Crypto: Allows for the creation of custom encryption.
■ Debugger: Allows debugging of a Node.js file.
■ DNS: Allows connections to DNS servers.
■ Errors: Allows for the handling of errors.
■ Events: Enables the handling of asynchronous events.
■ File system: Allows for file I/O with both synchronous and asynchronous methods
■ Globals: Makes frequently used modules available without having to include them first.
■ HTTPS: Enables HTTP over the TLS/SSL.
What Does Node.js Come With?
■ HTTP: Enables support for many HTTP features.
■ OS: Allows access to the operating system that Node.js is running on.
■ Path: Enables access to file and directory paths.
■ Process: Provides information and allows control over the current Node.js process.
■ Query strings: Allows for parsing and formatting URL queries.
■ Readline: Enables an interface to read from a data stream.
■ REPL: Allows developers to create a command shell.
■ Stream: Provides an API to build objects with the stream interface.
■ String decoder: Provides an API to decode buffer objects into strings.
■ Timers: Allows for scheduling functions to be called in the future.
■ TLS/SSL: Implements TLS and SSL protocols.
■ URL: Enables URL resolution and parsing.
■ Utilities: Provides support for various apps and modules.
■ V8: Exposes APIs for the Node.js version of V8.
■ VM: Allows for a V8 virtual machine to run and compile code.
■ ZLIB: Enables compression using Gzip and Deflate/Inflate.
Installing Node.js
• To easily install Node.js, download an installer from the Node.js website at http://nodejs.org.
The Node.js installer installs the necessary files on your PC to get Node.js up and running. No
additional configuration is necessary to start creating Node.js applications.
• Looking at the Node.js Install Location
• If you look at the install location, you will see a couple of executable files and a node_modules
folder. The node executable file starts the Node.js JavaScript VM. The following list describes
the executables in the Node.js install location that you need to get started:
■ node: This file starts a Node.js JavaScript VM. If you pass in a JavaScript file location, Node.js
executes that script. If no target JavaScript file is specified, then a script prompt is shown that
allows you to execute JavaScript code directly from the console.
■ npm: This command is used to manage the Node.js packages discussed in the next section.
■ node_modules: This folder contains the installed Node.js packages. These packages act as
libraries that extend the capabilities of Node.js.
Verify Node.js Executables
• . To do so, open a console prompt and execute the following command to bring up a Node.js VM:
node
• Next, at the Node.js prompt execute the following to write "Hello World" to the screen.
• >console.log("Hello World");
• You should see "Hello World" output to the console screen. Now exit the console using Ctrl+C in
Windows.
•Next, verify that the npm command is working by executing the following command in the OS console
prompt:
• npm version
You should see output similar to the following:
{ npm: '3.10.5',
ares: '1.10.1-DEV',
http_parser: '2.7.0',
icu: '57.1',
modules: '48',
node: '6.5.0',
openssl: '1.0.2h',
uv: '1.9.1',
v8: '5.1.281.81',
Selecting a Node.js IDE
Integrated Development Environment (IDE):
• Most developers are particular about the IDE that they like to use, and there will likely be a
way to configure at least for JavaScript if not Node.js directly. For example, Eclipse has
some great Node.js plugins, and the WebStorm IDE by IntelliJ has some good features for
Node.js built in.
• we use Visual Studio Code for the built-in TypeScript functionality required later in this
book.
• you can use any editor you want to generate your Node.js web applications. In reality, all you
need is a decent text editor.
• Almost all the code you will generate will be .js, json, .html, and .css.
• So pick the editor in which you feel the most comfortable writing those types of files.
Working with Node Packages
• One of the most powerful features of the Node.js framework is the ability to easily extend it with additional
Node Packaged Modules (NPMs) using the Node Package Manager (NPM).
• That’s right, in the Node.js world, NPM stands for two things. This book refers to the Node Packaged Modules
as modules to make it easier to follow.

• What Are Node Packaged Modules?


• A Node Packaged Module is a packaged library that can easily be shared, reused, and installed in different
projects. Many different modules are available for a variety of purposes. For example, the Mongoose
module provides an ODM (Operational Data Model) for MongoDB, Express extends Node’s HTTP
capabilities, and so on.
• Node.js modules are created by various third-party organizations to provide the needed features that
Node.js lacks out of the box. This community of contributors is active in adding and updating modules.
• Node Packaged Modules include a package.json file that defines the packages.
• The package. json file includes informational metadata, such as the name, version author,
and contributors, as well as control metadata, such as dependencies and other requirements that the
Node Package Manager uses when performing actions such as installation and publishing.
Understanding the Node Package Registry
• The Node modules have a managed location called the Node Package Registry where packages
are registered. This allows you to publish your own packages in a location where others can use them
as well as download packages that others have created.
• The Node Package Registry is located at https://npmjs.com. From this location you can view the
newest and most popular modules as well as search for specific packages, as shown in Figure 3.1.
Using the Node Package Manager
• The Node Package Manager you have already seen is a command-line utility. It allows you to
find, install, remove, publish, and do everything else related to Node Package Modules.
The Node Package Manager provides the link between the Node Package Registry and your
development environment.
• The simplest way to really explain the Node Package Manager is to list some of the command- line
options and what they do. Table 3.1 lists the Node Package Manager commands.
Searching for Node Package Modules
• You can also search for modules in the Node Package Registry directly from the command
prompt using the npm search <search_string> command. For example, the following
command searches for modules related to openssl and displays the results as shown:
• npm search openssl

• Installing Node Packaged Modules


• To use a Node module in your applications, it must first be installed where Node can find it. To
install a Node module, use the npm install <module_name> command. This downloads the
Node module to your development environment and places it into the node_modules folder
where the install command is run. For example, the following command installs the express
module:
•npm install express
• The output of the npm install command displays the dependency hierarchy installed with the
module. For example, the following code block shows part of the output from installing the
express module.
Using package.json
• All Node modules must include a package.json file in their root directory.
• The package.json file is a simple JSON text file that defines the module including
dependencies.
• The package. json file can contain a number of different directives to tell the Node
Package Manager how to handle the module.
• npm init command used to crate .json file
•The following is an example of a package.json file with a name, version, description, and
dependencies:
{
"name": "my_module",
"version": "0.1.0",
"description": "a simple node.js module", "dependencies" : {
"express" : "latest"
}
}
• The only required directives in the package.json file are name and version.
Packages used in .json file
Packages used in .json file
• A great way to use package.json files is to automatically download and install the
dependencies for your Node.js app. All you need to do is create a package.json file in the
root of your project code and add the necessary dependencies to it. For example, the
following package. json requires the express module as a dependency.
{
"name": "my_module",
"version": "0.1.0", "dependencies" : {
"express" : "latest"
}
}
•Then you run the following command from root of your package, and the express module is
automatically installed.
• npm install
• Notice that no module is specified in the npm install. That is because npm looks for a
package.json file by default. Later, as you need additional modules, all you need to do is
add those to the dependencies directive and then run npm install again.
Creating a Node.js Application
• Here are some prerequisites for a beginner to create the first Node.js application:
• Basic knowledge of JavaScript: Node.js is a JavaScript runtime, so it is essential to have a
basic understanding of JavaScript, including data types, variables, functions, loops, and
conditional statements.
• Command line basics: As you will be running your Node.js application from the command
line, it is necessary to have some knowledge of command-line basics, such as navigating
directories, creating and deleting files and directories, and running commands.
• Node.js installation: You will need to install Node.js on your computer. You can download
the installer from the official Node.js website and follow the installation instructions.
• Text Editor: You will need a text editor to write your Node.js code. There are several options
available, including Visual Studio Code, Atom, Sublime Text, etc. Choose the one that suits
you the best.
• Node Package Manager (NPM): NPM is a package manager that comes with Node.js,
allowing you to install and manage external modules easily. You will need to have some
understanding of NPM to install and use external modules in your Node.js application.
Creating a Node.js Application
• Create a new folder: Right click → New → Folder name(myproject)
→ enter.
• Open the folder you created in any text editor of your choice. Here,
we will be taking the reference of Visual Studio Code.
• Create a new file ‘index.js’ under your project folder in Visual Studio
Code.
• Open the index.js file with your preferred text editor and start
adding your Node.js code.
• const http = require('http');
• The statement const http = require('http');loads the http module and assigns it to the http
constant. This allows you to use the functions and objects provided by the http module
in your code.
• After this, add the below code lines
const server=http.createServer((req,res)=>{
res.write('Hello World!')
res.end()
})
• The createServer method takes a callback function as its argument, which is executed
every time the server receives an HTTP request. The callback function takes two
parameters, req**,** and res, which represent the incoming HTTP request and the
server's response, respectively.
• In the callback function, the res.write()method is called to write the "Hello World!"
message to the response.
• The res.end()method is called to end the response and send it back to the client.
• Finally, add these lines below to complete the first application.
server.listen(3000, () => {
console.log('Server running on port 3000');
});
• The listen method of the server object is called with two arguments: the
first argument is the port number (3000in this case) that the server should
listen on, and the second argument is a callback function that will be
executed when the server starts listening on the specified port.
• In the callback function, the message "Server running on port 3000" is
printed to the console using the console.log method.
// to print the message 'Hello World!
const http = require('http');
const server=http.createServer((req,res)=>{
// Text to the body
res.write('Hello World!')
// Telling server that all header and body response has been sent
res.end()
})
// Defining port for the server to run
server.listen(3000, () => {

//Message to print on the console after a successful run


console.log('Server running on port 3000');
});
// to print the message 'Hello World!

var http = require('http');


http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>hello world....</h1>');
res.end();

}).listen(3000);
• To run the file open a terminal on your editor and type the
following command
• node index.js
• The console of the text editor must show the message ‘Server
running on port 3000’
• To check if the server is actually running or not, navigate to your
browser, and on the address bar/URL bar type the below line and
hit enter.
• localhost:3000
Using Events, Listeners, Timers, and Callbacks in Node.js
• Understanding the Node.js Event Model
• Node.js applications are run in a single-threaded event-driven model. Although Node.js implements a thread
pool in the background to do work, the application itself doesn’t have any concept of multiple threads.
• Comparing Event Callbacks and Threaded Models
• In the traditional threaded web model, a request comes in to the webserver and is assigned to an available
thread. Then the handling of work for that request continues on that thread until the request is complete and
a response is sent.
• Figure 4.1 illustrates the threaded model processing two requests, GetFile and GetData. The GetFile
request first opens the file, reads the contents, and then sends the data back in a response. All this occurs in
order on the same thread.
The GetData request connects to the DB
, queries the necessary data, and then
sends the data in the response.
Comparing Event Callbacks and Threaded Models
• Instead of executing all the work for each request on individual threads, work is
added to an event queue and then picked up by a single thread running an event loop.
• The event loop grabs the top item in the event queue, executes it, and then grabs the
next item.
• When executing code that is no longer live or has blocking I/O, instead of calling the
function directly, the function is added to the event queue along with a callback that is
executed after the function completes.
• When all events on the Node.js event queue have been executed, the Node application
terminates.
Comparing Event Callbacks and Threaded Models

Figure 4.2 illustrates the way Node.js handles the GetFile and GetData requests.
The GetFile and GetData requests are added to the event queue. Node.js first picks up the GetFile
request, executes it, and then completes by adding the Open() callback function to the event queue.
Next, it picks up the GetData request, executes it, and completes by adding the Connect() callback
function to the event queue.
This continues until there are no callback functions to be executed.
Notice in Figure 4.2 that the events for each thread do not necessarily follow a direct interleaved order.
For example, the Connect request takes longer to complete than the Read request, so Send(file) is
called before Query(db)
Node.js event model
Events in Node.js
In Node.js applications, Events and Callbacks concepts are used to provide concurrency. As
Node.js applications are single threaded and every API of Node js are asynchronous. So it uses
async function to maintain the concurrency. Node uses observer pattern. Node thread keeps an
event loop and after the completion of any task, it fires the corresponding event which signals
the event listener function to get executed.
Event Driven Programming
Node.js uses event driven programming. It means as soon as Node starts its server, it simply
initiates its variables, declares functions and then simply waits for event to occur. It is the one
of the reason why Node.js is pretty fast compared to other similar technologies.
There is a main loop in the event driven application that listens for events, and then triggers a
callback function when one of those events is detected.
Events in Node.js

Although, Events and Callbacks look similar but the differences lies in the fact that callback
functions are called when an asynchronous function returns its result where as event
handling works on the observer pattern.
Whenever an event gets fired, its listener function starts executing.
Node.js has multiple in-built events available through events module and EventEmitter class
which is used to bind events and event listeners.
Events in Node.js
// Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
// Registering to myEvent
eventEmitter.on('myEvent', (msg) => {
console.log(msg);
});
// Triggering myEvent
eventEmitter.emit('myEvent', "First event");
// Triggering myEvent
eventEmitter.emit('myEvent', "Second event");
console.log("program ended...")
Output:
First event
Second event
program ended...
Events in Node.js
var events = require('events'); // Import events module
var eventEmitter = new events.EventEmitter(); // Create an eventEmitter object
// Create an event handler as follows
var connectHandler = function connected() {
console.log('connection succesful.');
eventEmitter.emit('data_received'); // Fire the data_received event
}
eventEmitter.on('connection', connectHandler); // Bind the connection event with the handler
// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function(){
console.log('data received succesfully.');
});
eventEmitter.emit('connection'); // Fire the connection event
console.log("Program Ended.");
Output:
connection succesful.
data received succesfully.
Program Ended.
Adding Work to the Event Queue
• In Node.js applications, work is scheduled on the event queue by passing a callback
function using one of these methods:
• Make a call to one of the blocking I/O library calls such as writing to a file or
connecting to a database.
• Add a built-in event listener to a built-in event such as an http.request or
server. connection.
• Create your own event emitters and add custom listeners to them.
• Use the process.nextTick option to schedule work to be picked up on the next
cycle of the event loop.
• Use timers to schedule work to be done after a particular amount of time or at
periodic intervals.
Implementing Timers
•A useful feature of Node.js and JavaScript is the ability to delay execution of code for a period of
time. There are three types of timers in Node.js: timeout, interval, and immediate.
•Delaying Work with Timeouts
•Timeout timers are used to delay work for a specific amount of time. When that time expires, the
callback function is executed and the timer goes away. Use timeouts for work that only needs to be
performed once.
•Timeout timers are created using the setTimeout(callback, delayMilliSeconds, [args]) method built
into Node.js.
•When you call setTimeout(), the callback function is executed after delayMilliSeconds expires.
•For example, the following executes myFunc() after 1 second:
•setTimeout(myFunc, 1000);
•The setTimeout() function returns a timer object ID. You can pass this ID to clearTimeout(timeoutId)
at any time before the delayMilliSeconds expires to cancel the timeout function.
•For example:
Delaying Work with Timeouts
• The syntax of implementing callback in Node.js is as follows −
• function function_name(argument, function (callback_argument){
// callback body
})
• The setTimeout() function in Node.js is a typical example of callback. The following code calls the
asynchronous setTimeout() method, which waits for 1000 milliseconds, but doesn't block the thread.
Instead, the subsequent Hello World message, followed by the timed message.
• ---------------------------------------------------------------
setTimeout(function () {
console.log('This prints after 1000 ms');
}, 1000);
console.log("Hello World");
• -------------------------------------------------------------------
• -Output
• Hello World
• This prints after 1000 ms
Performing Periodic Work with intervals
• Interval timers are used to perform work on a regular delayed interval. When the delay time expires, the
callback function is executed and is then rescheduled for the delay interval again. Use intervals for work that
needs to be performed on a regular basis.
• Interval timers are created using the setInterval(callback, delayMilliSeconds, [args])
method built into Node.js. When you call setInterval(), the callback function is executed every interval
after delayMilliSeconds has expired. For example, the following executes myFunc() every second:
• setInterval(myFunc, 1000);
• The setInterval() function returns a timer object ID.
• You can pass this ID to clearInterval(intervalId) at any time before the delayMilliSeconds
expires to cancel the timeout function.
• For example:
• myInterval = setInterval(myFunc, 100000);
• … clearInterval(myInterval);
Performing Periodic Work with intervals
Implementing Callbacks
• A Callback in Node.js is an asynchronous equivalent for a function. It is a special type of
function passed as an argument to another function. Node.js makes heavy use of callbacks.
Callbacks help us make asynchronous calls. All the APIs of Node are written in such a way
that they support callbacks.
• Programming instructions are executed synchronously by default. If one of the instructions in a
program is expected to perform a lengthy process, the main thread of execution gets blocked.
The subsequent instructions can be executed only after the current I/O is complete. This is
where callbacks come in to the picture.
• The callback is called when the function that contains the callback as an argument completes
its execution, and allows the code in the callback to run in the meantime. This makes Node.js
highly scalable, as it can process a high number of requests without waiting for any function to
return results.
• The syntax of implementing callback in Node.js is as follows −
• function function_name(argument, function (callback_argument){
// callback body
})
Implementing Callbacks
// call back function
var fs= require('fs')
fs.writeFile('file.txt','call back functions',function()
{
console.log(" data written to file.txt")
})
console.log('End of the program.....’)

Output:
End of the program.....
data written to file.txt
Implementing Callbacks
• The setTimeout() function in Node.js is a typical example of callback. The
following code calls the asynchronous setTimeout() method, which waits for
1000 milliseconds, but doesn't block the thread. Instead, the subsequent Hello
World message, followed by the timed message.
• ---------------------------------------------------------------
setTimeout(function () {
console.log('This prints after 1000 ms');
}, 1000);
console.log("Hello World");
• -------------------------------------------------------------------
• -Output
• Hello World
• This prints after 1000 ms

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy