Unit I
Unit I
1. Saves time: The most striking feature of web framework is that it saves time and energy
in developing any app because the developer doesn't need to worry about session
handling, error handling and authentication logic. These functions are taken care of by
web frameworks.
2. Well organized app: The web framework itself takes care of managing directories and files.
This makes the complete application well organized.
5. Security: Framework makes developers sure that the application uses good security
measurements because the framework itself takes care of it.
Web Development Framework
A web development framework is a set of tools and resources that help developers build
and manage websites, web applications, and web services.
Frameworks can help with tasks like:
Database interaction
URL routing
User authentication
Security
Push notifications
Code reusability
Generating HTML from templates
Formatting data as JSON or XML
There are two types of web frameworks:
Client-side framework: Works in the front end and manages the user interface
Server-side framework: Works in the background and ensures the website functions
smoothly
Web Development Framework
A web development framework is a collection of tools, libraries, and technologies used to
create web applications. It simplifies and standardizes the development process.
Browser-to-Webserver Communication
Browser-to-webserver communication consists of a series of requests, using the HTTP and
HTTPS protocols.
Hypertext Transfer Protocol (HTTP) is used to define communication between the browser
and the webserver.
HTTP defines what types of requests can be made as well as the format of those requests
and the HTTP response.
Difference between http:// and https://
• When browsing the web, you might have noticed URLs starting with
http. It is either ‘http://’ or ‘https://’. Such prefixes show how data is
transmitted between your browser and the website that you are
accessing. HTTP and HTTPS are both protocols for communication
but they are different in several ways and the main difference is
security. This article will define HTTP and HTTPS as well as their
features and why HTTPS is more frequently used than HTTP.
What is HTTP?
There are three main types of requests that a browser will make to a webserver:
■ 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
that is done directly by JavaScript running in the browser. Despite the name, an AJAX
request can receive XML, JSON, or raw data in the response.
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, 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
Rendering the Browser View
The browser interprets each DOM element and renders it to the user’s screen to build the
webpage view. The browser often gets various types of data from multiple webserver
requests to build a webpage.
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, in terms of
font, color, borders, and spacing.
■ Client-side scripts: These are typically JavaScript files. They can provide added
functionality to a 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: Data such as XML, JSON, or raw text can be provided by the webserver as a
response to an AJAX request. Rather than send a request back to the server to rebuild
the webpage, new data can be retrieved via AJAX and inserted into the webpage via
JavaScript.
■ HTTP headers: HTTP defines a set of headers that the browser can use and client-side
scripts to define the behavior of the webpage. For example, cookies are contained in the
HTTP headers. The HTTP headers also define the type of data in the request as well as the
type of data expected to be returned to the browser.
User Interaction
The user interacts with the browser via mice, keyboards, and touchscreens. A browser has
an elaborate event system that captures user input events and then takes the appropriate
actions.
Actions vary from displaying a popup menu to loading a new document from the server to
executing client-side JavaScript.
Webservers
A webserver’s main focus is handling requests from browsers. As described earlier, a browser
may request a document, post data, or perform an AJAX request to get data. The webserver
uses HTTP headers as well as a URL to determine what action to take. This is where things
get very different, depending on the webserver, configuration, and technologies used.
Most out-of-the-box 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.
A server-side script is really anything that a webserver can execute in order to perform the
task the browser is requesting. These scripts can be written in PHP, Python, C, C++, C#, Perl,
Java, ... the list goes on and on. 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.
This is where having a solid webserver framework can make a big difference. It often takes
quite a bit of configuration to enable various scripting languages and wire up the server-side
scripts so that the webserver can route the appropriate requests to the appropriate scripts.
Server-side scripts either generate a 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 responses.
Backend Services
Backend services are services that run behind a webserver and provide data that is 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.
On the other hand, 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.
MERN Stack
MERN is a pre-built technology stack based on JavaScript technologies.
MERN stands for MongoDB, Express, React, and Node, after the four key technologies
that make up the stack.
That's where MongoDB comes in: JSON documents created in your React.js front end can be sent to the Express.js
server, where they can be processed and (assuming they're valid) stored directly in MongoDB for later retrieval.
MEAN stack
MongoDB: A NoSQL, object-oriented database designed for use with cloud applications
Express(.js): A web application framework for Node(.js) that supports interactions between
the front end (e.g., the client side) and the database
Angular(.js): Often referred to as the “front end"; a client-side JavaScript framework used
to create dynamic web applications to work with interactive user interfaces
Node(.js): The premier JavaScript web server used to build scalable network applications
MEAN Vs MERN
The frontend framework for MEAN stack is The frontend framework for the MERN stack is The frontend framework for the full stack can be
Angular React Angular, React, or Vue.js.
The backend framework for the MEAN stack is The backend framework for the MERN stack is The backend framework for full stack can be
Express.js Express.js Express.js, Django, and Spring Boot.
It uses JavaScript as primary language for The MERN stack primary language is The full-stack primary language can be Java or
front-end and back-end JavaScript (for both front-end and back-end) Javascript or Python.
Angular’s two-way data binding can be less React’s virtual DOM often offers better The performance varies widely with stack choice
effective performance and optimization; stacks may optimize differently
Understanding the Node.js-to-AngularJS Stack Components
With the basic structure of the web framework fresh in your mind, it is time to discuss the
Node.js-to-AngularJS stack.
The most common—and I believe the best—version of this stack is the Node.js-to-
AngularJS stack comprised of MongoDB, Express, AngularJS, and Node.js.
In the Node.js-to-AngularJS 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 AngularJS framework.
AngularJS is an MVC framework in which the model is made up of JSON or JavaScript
objects, the view is HTML/CSS, and the controller is AngularJS JavaScript code.
Figure 1.2 provides a very basic diagram of how the Node.js to AngularJS stack fits into the
basic website/web application model. The following sections describe each of these
technologies and why they were chosen as part of the Node.js to AngularJS stack. Later
chapters in the book will cover each of the technologies in much more detail.
Basic diagram showing where Node.js, Express, MongoDB, and AngularJS fit in the
web paradigm
Node.js
Node.js is a development framework that is based on Google’s V8 JavaScript engine and executes it. You
can write most—or maybe even all—of your server-side code in Node.js, including the webserver and the
server-side scripts and any supporting web application functionality. The fact that the webserver and the
supporting web application scripts are running together in the same server-side application allows for much
tighter integration between the webserver and the scripts. Also, the webserver can run directly on the
Node.js platform as a Node.js module, which means it’s much easier than using, say, Apache for wiring up
new services or server-side scripts.
The following are just a few reasons Node.js is a great framework:
■ JavaScript end-to-end: One of the biggest advantages of Node.js is that it allows you to write both server-
and client-side scripts in JavaScript. There have always been difficulties in deciding whether to put logic in
client-side scripts or server-side scripts. With Node.js you can take JavaScript written on the client and
easily adapt it for the server and vice versa. An added plus is that client developers and server developers
are speaking the same language.
■ Event-driven scalability: Node.js applies a unique logic to handling web requests. Rather than having
multiple threads waiting to process web requests, with Node.js they are processed on the same thread,
using a basic event model. This allows Node.js webservers to scale in ways that traditional webservers
can’t.
■ Extensibility: Node.js has a great following and very active development community. People are providing
new modules to extend Node.js functionality all the time. Also, it is very simple to install and include new
modules in Node.js; you can extend a Node.js project to include new functionality in minutes.
■ Fast implementation: Setting up Node.js and developing in it are super easy. In only a few minutes you
can install Node.js and have a working webserver.
MongoDB
MongoDB is an agile and very scalable NoSQL database. The name Mongo comes from
the word “hu mongo us,” emphasizing the scalability and performance MongoDB provides.
It is based on the NoSQL document store model, which means data is stored in the
database as basically JSON objects rather than as 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 quickly scalable and
easy to implement. This book covers using the MongoDB driver library to access MongoDB
from Node.js.
Node.js supports a variety of database access drivers, so the data store can easily be
MySQL or some other database. 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, data is stored in the
database in a format that is very close to what you deal 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, with more and more people interacting with websites, it is important to
have a backend that can support heavy traffic.
■ High availability: MongoDB’s replication model makes it very easy to maintain scalability
while keeping high performance.
■ High scalability: MongoDB’s structure makes it easy to scale horizontally by sharding
the data across multiple servers.
Express
The Express module acts as the webserver in the Node.js-to-AngularJS stack. Because it runs in
Node.js, it is easy to configure, implement, and control. The Express module extends Node.js to
provide several key components for handling web requests. It allows you to implement a running
webserver in Node.js with only a few lines of code.
For example, the Express module provides the ability to easily set up destination routes (URLs)
for users to connect to. It also provides great functionality in terms of working with HTTP request
and response objects, including things like cookies and HTTP headers.
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
the Node.js script functionality on the server.
■ Error handling: Express provides built-in error handling for “document 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 you to easily integrate it into your existing
secured system.
■ Cookies: Express provides easy cookie management.
■ Session and cache management: Express also enables session management and cache
management.
AngularJS
AngularJS is a client-side framework developed by Google. It 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 in JavaScript, with a reduced jQuery library. The theory behind
AngularJS is to provide a framework that makes it easy to implement web applications using the MVC
framework.
Other JavaScript frameworks could be used with the Node.js platform, such as Backbone, Ember, and
Meteor. However, AngularJS has the best design, feature set, and trajectory at this writing. Here are
some of the benefits AngularJS provides:
■ Data binding: AngularJS has a very clean method for binding data to HTML elements, using its
powerful scope mechanism.
■ Extensibility: The AngularJS architecture allows you to easily extend almost every aspect of the
language to provide your own custom implementations.
■ Clean: AngularJS forces you to write clean, logical code.
■ Reusable code: The combination of extensibility and clean code makes it very easy to write reusable
code in AngularJS. In fact, the language often forces you to do so when creating custom services.
■ Support: Google is investing a lot into this project, which gives it an advantage over similar initiatives
that have failed.
■ Compatibility: AngularJS is based on JavaScript and has a close relationship with jQuery.
This makes it easier to begin integrating AngularJS into your environment and reuse pieces of your
existing code within the structure of the AngularJS framework.
JavaScript
The programs in this language are called scripts. They can be written right in a web page’s
HTML and run automatically as the page loads.
Scripts are provided and executed as plain text. They don’t need special preparation or
compilation to run.
Today, JavaScript can execute not only in the browser, but also on the server, or actually on
any device that has a special program called the JavaScript engine.
The browser has an embedded engine sometimes called a “JavaScript virtual machine”.
Different engines have different “codenames”.
For example:
V8 – in Chrome, Opera and Edge.
SpiderMonkey – in Firefox.
“Chakra” for IE,
“JavaScriptCore”, “Nitro” and “SquirrelFish” for Safari, etc.
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().
The example below "finds" an HTML element (with id=“CSE"), and changes the element
content (innerHTML) to “My first JavaScript":
<html>
<body>
<h2>What Can JavaScript Do?</h2>
</body>
</html>
JavaScript Can Change HTML Content
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="CSE1">First Line of JavaScript.</p>
<p id="CSE2">Second Line of JavaScript.</p>
<button type="button"
onclick='document.getElementById("CSE1").innerHTML
= "Changed First Line JavaScript!"'>Click Here
First!</button>
<button type="button"
onclick='document.getElementById("CSE2").innerHTML
= "Changed Second Line JavaScript!"'>Click Here
Second!</button>
</body>
</html>
JavaScript can change the style, can hide and show
hidden elements
<html><body>
<p id="cse1">JavaScript can change the style of an HTML
element.</p>
<button type="button"
onclick="document.getElementById('cse1').style.fontSize='
35px'">Click First!</button>
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. These companies
use Node.js first and foremost for scalability but also for ease of maintenance and faster
development. The following are just a few of the companies using the Node.js technology:
■ Yahoo!
■ LinkedIn
■ eBay
■ New York Times
■ Dow Jones
■ Microsoft
What Is Node.js Used For?
Node.js can be used for a wide variety of purposes. Because it is based on V8 and has
highly
optimized code to handle HTTP traffic, the most common use is as a webserver. However,
Node.js can also be used for a variety of other web services such as:
■ Web services APIs such as REST
■ Real-time multiplayer games
■ Backend web services such as cross-domain, server-side requests
■ Web-based applications
■ Multiclient communication such as IM
What Does Node.js Come With?
Node.js comes with many built-in modules available right out of the box. This book covers
many but not all of these modules:
■ Assertion testing: Allows you to test functionality within your code.
■ Buffer: Enables interaction with TCP streams and file system operations. (See Chapter 5,
“Handling Data I/O in Node.js.”)
■ 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. (See Chapter 9, “Scaling
Applications Using Multiple Processors in Node.js.”)
■ Cluster: Enables the use of multicore systems. (See Chapter 9.)
■ 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. (See Chapter 10, “Using Additional
Node.js Modules.”)
■ Debugger: Allows debugging of a Node.js file.
■ DNS: Allows connections to DNS servers. (See Chapter 10.)
■ Errors: Allows for the handling of errors.
■ Events: Enables the handling of asynchronous events. (See Chapter 4, “Using Events,
Listeners, Timers, and Callbacks in Node.js.”)
■ File system: Allows for file I/O with both synchronous and asynchronous methods.
(See Chapter 6, “Accessing the File System from Node.js.”)
■ Globals: Makes frequently used modules available without having to include them first.
(See Chapter 10.)
■ HTTP: Enables support for many HTTP features. (See Chapter 7, “Implementing HTTP
Services in Node.js.”)
■ HTTPS: Enables HTTP over the TLS/SSL. (See Chapter 7.)
Modules: Provides the module loading system for Node.js. (See Chapter 3.)
■ Net: Allows the creation of servers and clients. (See Chapter 8, “Implementing Socket
Services in Node.js.”)
■ OS: Allows access to the operating system that Node.js is running on. (See Chapter 10.)
■ Path: Enables access to file and directory paths. (See Chapter 6.)
■ Process: Provides information and allows control over the current Node.js process.
(See Chapter 9.)
■ Query strings: Allows for parsing and formatting URL queries. (See Chapter 7.)
■ Readline: Enables an interface to read from a data stream. (See Chapter 5.)
■ REPL: Allows developers to create a command shell.
■ Stream: Provides an API to build objects with the stream interface. (See Chapter 5.)
■ String decoder: Provides an API to decode buffer objects into strings. (See Chapter 5.)
■ Timers: Allows for scheduling functions to be called in the future. (See Chapter 4.)
■ TLS/SSL: Implements TLS and SSL protocols. (See Chapter 8.)
■ URL: Enables URL resolution and parsing. (See Chapter 7.)
■ Utilities: Provides support for various apps and modules.
■ V8: Exposes APIs for the Node.js version of V8. (See Chapter 10.)
■ VM: Allows for a V8 virtual machine to run and compile code.
■ ZLIB: Enables compression using Gzip and Deflate/Inflate. (See Chapter 5.)
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.
Download nodejs: https://nodejs.org
var http = require('http’);//To include a module, use the require() function with the name of
the module
http.createServer(function (req, res) {// Create an HTTP server
// Write the HTTP response header
// Status code 200 indicates success
// 'Content-Type': 'text/html' specifies the content type of the response
res.writeHead(200, {'Content-Type': 'text/html’});
res.end('Hello World!');
}).listen(8080);
Create Your Own Modules
You can create your own modules and easily include them in your applications.
First.js
datej.js
Download a Package
Downloading a package is very easy.
Open the command line interface and tell NPM to download the package you want.
Command Prompt
Using a Package
var uc = require('upper-case’);
res.write(uc.upperCase("Hello World!"));
res.end();
}).listen(8080);
Creating user defined modules and fuctions
datej.js
first.js
function add(a,b){
return a+b var datej = require('./datej');
}
exports.add = add result=datej.add(5,7)
console.log("The output is = "+result)
function sub(a,b){
return a-b result=datej.sub(7,5)
} console.log("The output is = "+result)
exports.sub = sub
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).
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.
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.
The Node Package Manager 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.
npm command-line options (with express as the package, where appropriate)
Understanding the Node Package Registry
Command Prompt
Directives used in the package.json file
Directives used in the package.json file