Advance App Development

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

Advanced Application Development

UNIT-1

Chapter-1 NodeJS
Q1. What is NodeJS? Explain advantages and disadvantages of NodeJS.

Node.js is a cross-platform runtime environment and library for running JavaScript applications outside the
browser. It is used for creating server-side and networking web applications. It is open source and free to use.

Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft
Windows, and Linux.

Advantages

High Performance
One of the most important features of node.js is the ability to create lightning-fast apps that produce results in
seconds.
Easy to Learn
It will be lot easier for them to get started using Node.js on the backend. It is simpler to understand Node.js,
and working with it takes less time.
Cost-Effective
Node.js allows programmers to develop server-side JavaScript and frontend JavaScript codes with simplicity.
One of the major node.js advantages is that it eliminates the need for two resource teams, saving time,
money, and energy for overall project development.
Extensibility
Node.js offers a lot of extensibility, which means it can be changed and improved to fit unique requirements.

Disadvantages

Unstable API
The Application Programming Interface changes frequently and is not reliable, which is one of the most
prevalent challenges that most developers experience.
Lack Of Library Support
In comparison to any other programming language, JavaScript lacks a well-equipped and robust library
system.
Asynchronous Programming Model:
If you want to boost the scalability of the application, the requirement is that the application should adopt an
asynchronous programming model.

Q2. What is NodeJS? Explain features of NodeJS.

Node.js is a cross-platform runtime environment and library for running JavaScript applications outside the
browser. It is used for creating server-side and networking web applications. It is open source and free to use.

Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft
Windows, and Linux.
Features:

Open source: Node.js has an open source community which has produced many excellent modules to add
additional capabilities to Node.js applications.

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.

Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution.

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.

No Buffering − Node.js applications never buffer any data. These applications simply output the data in
chunks.

License − Node.js is released under the MIT license.

Q3. State & Explain the steps to installing NodeJS ?

To install and setup an environment for Node.js, you need the following two softwares available on your
computer:

1. Text Editor.

2. Node.js Binary installable

Text Editor:

The text editor is used to type your program. For example: Notepad is used in Windows, vim or vi can be used
on Windows as well as Linux or UNIX.

The Node.js Runtime:

The source code written in source file is simply JavaScript. It is interpreted and executed by the Node.js
interpreter.

Step 1) Download Node.js Installer for Windows


Go to the site https://nodejs.org/en/download/ and download the necessary binary files.

In our example, we are going to Download Node.js on Windows with the 32-bit setup files.

Step 2) Run the installation

Double click on the downloaded .msi file to start the installation.

Click the Run button on the first screen to begin the installation.

Step 3) Continue with the installation steps


In the next screen, click the “Next” button to continue with the installation

Step 4) Accept the terms and conditions


In the next screen, Accept the license agreement and click on the Next button.

Step 5) Set up the path

In the next screen, choose the location where Node.js needs to be installed and then click on the Next button.

1. First, enter the file location for the installation of Node.js. This is where the files for Node.js will be stored
after the installation.

2. Click on the Next button to proceed ahead with the installation.

Step 6) Select the default components to be installed

Accept the default components and click on the Next button.

Step 7) Start the installation

In the next screen, click the Install button to start installing Node.js on Windows.

Step 8) Complete the installation

Click the Finish button to complete the installation.

Q4. Write a short note on Event Loop?

Node.js is a single-threaded application, but it can support concurrency via the concept of event and callbacks.
Every API of Node.js is asynchronous and being single-threaded, they use async function calls to maintain
concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever a task gets
completed, it fires the corresponding event which signals the event-listener function to execute.

Event Process
Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other
similar technologies. As soon as Node starts its server, it simply initiates its variables, declares functions and
then simply waits for the event to occur.
In an event-driven application, there is generally a main loop that listens for events, and then triggers a
callback function when one of those events is detected.
Although events look quite similar to callbacks, the difference lies in the fact that callback functions are called
when an asynchronous function returns its result, whereas event handling works on the observer pattern. The
functions that listen to events act as Observers.

Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events
available through events module and EventEmitter class which are used to bind events and event-listeners as
follows –

// Import events module


var events = require('events');

// Create an eventEmitter object


var eventEmitter = new events.EventEmitter();

Q5. Write a short note on Module in NodeJS?

A module in Node.js is a logical encapsulation of code in a single unit. It’s always a good programming practice
to always segregate code in such a way that makes it more manageable and maintainable for future purposes.
That’s where modules in Node.js comes in action.

Below are some of the popular modules which are used in a Node js application

1. Express framework – Express is a minimal and flexible Node js web application framework that
provides a robust set of features for the web and mobile applications.
2. Socket.io – Socket.IO enables real-time bidirectional event-based communication. This module is
good for creation of chatting based applications.
3. Jade – Jade is a high-performance template engine and implemented with JavaScript for node and
browsers.
4. MongoDB – The MongoDB Node.js driver is the officially supported node.js driver for MongoDB.
5. Restify – restify is a lightweight framework, similar to express for building REST APIs
6. Bluebird – Bluebird is a fully-featured promise library with a focus on innovative features and
performance

Q6. What is Http Module? Explain with example.

To make HTTP requests in Node.js, there is a built-in module HTTP in Node.js to transfer data over the HTTP.
To use the HTTP server in node, we need to require the HTTP module. The HTTP module creates an HTTP
server that listens to server ports and gives a response back to the client.
Syntax:
var http = require('http');
We can create a HTTP server with the help of http.createServer() method.
Example 1:
Filename: max.js

var http = require('http');

// Create a server
http.createServer((request, response)=>{

// Sends a chunk of the response body


response.write('Hello World!');

// Signals the server that all of


// the response headers and body
// have been sent
response.end();
})
.listen(3000); // Server listening on port 3000

Step to run this program: Run this max.js file using the below command:
node max.js
Output:

Server Started on port 3000

Q6.What is Web Module? Explain Web Application Architecture.

Web Server is a software program that handles HTTTP requests sent by HTTP clients like web browsers, and
returns web pages in response to the clients. Web servers usually respond with html documents along with
images, style sheets and scripts.

Most of the web server support server side scripts using scripting language or redirect to application server
which perform the specific task of getting data from database, perform complex logic etc. and then sends a
result to the HTTP client through the Web server.

Apache web server is one of the most commonly used web server. It is an open source project.

Web Application Architecture

A web application can be divided in 4 layers:


o Client Layer: The Client layer contains web browsers, mobile browsers or applications which can
make HTTP request to the web server.

o Server Layer: The Server layer contains Web server which can intercepts the request made by clients
and pass them the response.

o Business Layer: The business layer contains application server which is utilized by web server to do
required processing. This layer interacts with data layer via data base or some external programs.

o Data Layer: The Data layer contains databases or any source of data.

Chapter-2 MongoDB

7.What is MongoDB? Why use MongoDB.

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

In simple words, you can say that - Mongo DB is a document-oriented database. It is an open source product,
developed and supported by a company named 10gen.

MongoDB is available under General Public license for free, and it is also available under Commercial license
from the manufacturer.

The manufacturing company 10gen has defined MongoDB as:

"MongoDB is a scalable, open source, high performance, document-oriented database." - 10gen


MongoDB was designed to work with commodity servers. Now it is used by the company of all sizes, across all
industry.

Why Use MongoDB?


 Document Oriented Storage − Data is stored in the form of JSON style documents.
 Index on any attribute
 Replication and high availability
 Auto-Sharding
 Rich queries
 Fast in-place updates
 Professional support by MongoDB
Where to Use MongoDB?
 Big Data
 Content Management and Delivery
 Mobile and Social Infrastructure
 User Data Management
 Data Hub
Q8. State and Explain MongoDB features in details?

Features of MongoDB

These are some important features of MongoDB:

1. Support ad hoc queries

In MongoDB, you can search by field, range query and it also supports regular expression searches.

2. Indexing

You can index any field in a document.

3. Replication

MongoDB supports Master Slave replication. A master can perform Reads and Writes and a Slave copies data
from the master and can only be used for reads or back up (not writes)

4. Duplication of data

MongoDB can run over multiple servers. The data is duplicated to keep the system up and also keep its
running condition in case of hardware failure.

5. Load balancing

It has an automatic load balancing configuration because of data placed in shards.

6. Supports map reduce and aggregation tools.

7. Uses JavaScript instead of Procedures.

8. It is a schema-less database written in C++.

9. Provides high performance.

10. Stores files of any size easily without complicating your stack.
11. Easy to administer in the case of failures.

12. It also supports:

JSON data model with dynamic schemas

Auto-sharding for horizontal scalability

Built in replication for high availability

9.Write a short note on MongoDB Shell interface with example?

MongoDB Shell

MongoDB have a JavaScript shell that allows interaction with MongoDB instance from the command line.

If you want to create a table, you should name the table and define its column and each column's data type.

The shell is useful for performing administrative functions and running instances.

How to run the shell

To start the shell, open command prompt, run it as a administrator then run the mongo executable:

$ mongo

output

MongoDB shell version: 2.4.0


Connecting to: test

You should start mongoDB

before starting the shell because shell automatically attempt to connect to a MongoDB server on startup.

The shell is a full-featured JavaScript interpreter. It is capable of running Arbitrary JavaScript

program.

simple mathematical program:

1. >x= 100
2. 100
3. >x/ 5;
4. 20

Q10. What MongoDB Compass? Now to managing document in Compass?

MongoDB Compass
MongoDB Compass is a GUI for MongoDB. It is also known as MongoDB GUI. MongoDB allows users to analyze
the content of their stored data without any prior knowledge of MongoDB query syntax. When we explore
exploring our data in the visual environment, we can use Compass GUI to optimize performance, manage
indexes, and implement document-validation.

Available Compass Edition

MongoDB GUI

is available in the following four editions:

o Compass Community: This edition is designed for developing with MongoDB and includes a subset of
the features of Compass.

o Compass: It is released as the full version of MongoDB Compass. It includes all the features and
capabilities that MongoDB provides.

o Compass Randomly: It is limited to read operation only with all update and delete capabilities
removed.

o Compass Isolated: The Isolated edition of MongoDB compass doesn't start any network requests
except to the MongoDB server to which MongoDB GUI connects. It is designed to use in highly secure
environments.

Managing Documents in MongoDB Compass

Documents are the records in a MongoDB collection. Documents are the basic unit of data in MongoDB. Using
the document tab, we can perform the following tasks in our selected collection or view:

o View the documents: The Document tab provides three ways to access document in MongoDB
Compass.

o List View - It is the default view of the Database in the MongoDB Compass. Document will be
shown as individual members of the list. In the list view you can easily extend the embedded
objects and arrays.

o JSON View - In this view documents will be shown as completely-formatted JSON objects. In
this view, MongoDB Compass use extended JSON to display the data-types of field where the
correct data types are used.

o Table View - The table view display documents as a table row. The document fields are
shown as a column in the table. When we use table view, we can easily find out the
documents that contains specific field values.

Q11. Creating ,inserting,updateing and Deleting document using MongoDB ?

The insert() Method


To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.
Syntax
The basic syntax of insert() command is as follows −
>db.COLLECTION_NAME.insert(document)

MongoDB's update() and save() methods are used to update document into a collection. The update() method
updates the values in the existing document while the save() method replaces the existing document with the
document passed in save() method.
MongoDB Update() Method
The update() method updates the values in the existing document.
Syntax
The basic syntax of update() method is as follows −
>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)

The remove() Method


MongoDB's remove() method is used to remove a document from the collection. remove() method accepts
two parameters. One is deletion criteria and second is justOne flag.
 deletion criteria − (Optional) deletion criteria according to documents will be removed.
 justOne − (Optional) if set to true or 1, then remove only one document.
Syntax
Basic syntax of remove() method is as follows −
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

Remove Only One


If there are multiple records and you want to delete only the first record, then set justOne parameter
in remove() method.

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
Remove All Documents
If you don't specify deletion criteria, then MongoDB will delete whole documents from the collection. This is
equivalent of SQL's truncate command.

> db.mycol.remove({})
WriteResult({ "nRemoved" : 2 })
> db.mycol.find()

Q12. How to find Document using Query document using MongoDB?

Following methods to find document in MongoDB database

The find() Method


To query data from MongoDB collection, you need to use MongoDB's find() method.
Syntax
The basic syntax of find() method is as follows −
>db.COLLECTION_NAME.find()
find() method will display all the documents in a non-structured way.
Example
Assume we have created a collection named mycol as −

> use sampleDB


switched to db sampleDB
> db.createCollection("mycol")
{ "ok" : 1 }

The pretty() Method


To display the results in a formatted way, you can use pretty() method.
Syntax
>db.COLLECTION_NAME.find().pretty()

The findOne() method


Apart from the find() method, there is findOne() method, that returns only one document.
Syntax
>db.COLLECTIONNAME.findOne()

----------------------------------------------------------Unit-1 Ends Here------------------------------------------------------------------


-

UNIT-2
Chaptor-4 Server-Side Development with Express (E)

Q1.What is AngularJS ? Explain features in details.

Angular JS is an open source JavaScript framework that is used to build web applications. It can be freely used,
changed and shared by anyone.

Angular Js is developed by Google.

It is an excellent framework for building single phase applications and line of business applications.

AngularJS is a very powerful JavaScript Framework. It is used in Single Page Application (SPA) projects.

It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is
open source, completely free, and used by thousands of developers around the world.
Core Features
The core features of AngularJS are as follows −
 Data-binding − It is the automatic synchronization of data between model and view
components.
 Scope − These are objects that refer to the model. They act as a glue between controller and
view.
 Controller − These are JavaScript functions bound to a particular scope.
 Services − AngularJS comes with several built-in services such as $http to make a
XMLHttpRequests. These are singleton objects which are instantiated only once in app.
 Filters − These select a subset of items from an array and returns a new array.
 Directives − Directives are markers on DOM elements such as elements, attributes, css, and
more. These can be used to create custom HTML tags that serve as new, custom widgets.
AngularJS has built-in directives such as ngBind, ngModel, etc.
 Templates − These are the rendered view with information from the controller and model.
These can be a single file (such as index.html) or multiple views in one page using partials.
 Routing − It is concept of switching views.

Q2. What AngularJS? Explain advantages and disadvantages of AngularJS.

Angular JS is an open source JavaScript framework that is used to build web applications. It can be freely used,
changed and shared by anyone.

Angular Js is developed by Google.

It is an excellent framework for building single phase applications and line of business applications.

AngularJS is a very powerful JavaScript Framework. It is used in Single Page Application (SPA) projects.

It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is
open source, completely free, and used by thousands of developers around the world.

Advantages of AngularJS
The advantages of AngularJS are −
 It provides the capability to create Single Page Application in a very clean and maintainable
way.
 It provides data binding capability to HTML. Thus, it gives user a rich and responsive
experience.
 AngularJS code is unit testable.
 AngularJS uses dependency injection and make use of separation of concerns.
 AngularJS provides reusable components.
 With AngularJS, the developers can achieve more functionality with short code.
 In AngularJS, views are pure html pages, and controllers written in JavaScript do the business
processing.
Disadvantages of AngularJS
Though AngularJS comes with a lot of merits, here are some points of concern −
 Not Secure − Being JavaScript only framework, application written in AngularJS are not safe.
Server side authentication and authorization is must to keep an application secure.
 Not degradable − If the user of your application disables JavaScript, then nothing would be
visible, except the basic page.

Q3.State and Explain Angular MVC Architecture?


Model View Controller or MVC as it is popularly called, is a software design pattern for developing web
applications. A Model View Controller pattern is made up of the following three parts −
 Model − It is the lowest level of the pattern responsible for maintaining data.
 View − It is responsible for displaying all or a portion of the data to the user.
 Controller − It is a software Code that controls the interactions between the Model and View.

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.
Q4. What is AngularJS Data Binding? How to implement One and Two way Data Binding.

Data binding is a very useful and powerful feature used in software development technologies. It acts as a
bridge between the view and business logic of the application.AngularJS follows Two-Way data binding model.

One-Way Data Binding

The one-way data binding is an approach where a value is taken from the data model and inserted into an
HTML element. There is no way to update model from view. It is used in classical template systems. These
systems bind data in only one direction.
Two-Way Data Binding

Data-binding in Angular apps is the automatic synchronization of data between the model and view
components.

Data binding lets you treat the model as the single-source-of-truth in your application. The view is a projection
of the model at all times. If the model is changed, the view reflects the change and vice versa.

For Example

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="" ng-init="firstName='Ajeet'">
<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>
</div>
</body>
</html>

Q5. What is AngularJS Directives? Explain types of Directives.

AngularJS Directives

AngularJS facilitates you to extend HTML with new attributes. These attributes are called directives.

There is a set of built-in directive in AngularJS which offers functionality to your applications. You can also
define your own directives.

Directives are special attributes starting with ng- prefix. Following are the most common directives:

o ng-app: This directive starts an AngularJS Application.

o ng-init: This directive initializes application data.

o ng-model: This directive defines the model that is variable to be used in AngularJS.

o ng-repeat: This directive repeats html elements for each item in a collection.

1.ng-app directive

ng-app directive defines the root element. It starts an AngularJS Application and automatically initializes or
bootstraps the application when web page containing AngularJS Application is loaded. It is also used to load
various AngularJS modules in AngularJS Application.

example:

In following example, we've defined a default AngularJS application using ng-app attribute of a div element.

<div ng-app = "">


...
</div>

2.ng-init directive

ng-init directive initializes an AngularJS Application data. It defines the initial values for an AngularJS
application.

In following example, we'll initialize an array of countries. We're using JSON syntax to define array of
countries.

<div ng-app = "" ng-init = "countries = [{locale:'en-IND',name:'India'}, {locale:'en-


PAK',name:'Pakistan'}, {locale:'en-AUS',name:'Australia'}]">
...
</div>
3.ng-model directive:

ng-model directive defines the model/variable to be used in AngularJS Application.

In following example, we've defined a model named "name".

<div ng-app = "">


...
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
</div>
4.ng-repeat directive

ng-repeat directive repeats html elements for each item in a collection. In following example, we've iterated
over array of countries.

<div ng-app = "">


...
<p>List of Countries with locale:</p>

<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>

Q6. Write a short note on AngularJS Module?

AngularJS Module
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.
How to create a module

The angular object's module() method is used to create a module. It is also called AngularJS function
angular.module

<div ng-app="myApp">...</div>
<script>
var app = angular.module("myApp", []);
</script>
Here, "myApp" specifies an HTML element in which the application will run. Now we can add controllers,
directives, filters, and more, to AngularJS application.

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

If you want to add a controller to your application refer to the controller with the ng-controller directive.

example:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "Ajeet";
$scope.lastName = "Maurya";
});
</script>
</body>
</html>

Q7. Write a short note on Dependency Injection in AngularJS?

Dependency Injection is a software design in which components are given their dependencies instead of hard
coding them within the component. It relieves a component from locating the dependency and makes
dependencies configurable. It also helps in making components reusable, maintainable and testable.
AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which
can be injected into each other as dependencies.

 Value
 Factory
 Service
 Provider
 Constant
Value
Value is a simple JavaScript object, which is required to pass values to the controller during config phase
(config phase is when AngularJS bootstraps itself).
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.
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.
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.
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");

Q8 Explain the steps to execute AngularJS Application?

Creating AngularJS Application


Step 1: Load framework
Being a pure JavaScript framework, it can be added using <Script> tag.
<script
src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
Step 2: Define AngularJS application using ng-app directive
<div ng-app = "">
...
</div>
Step 3: Define a model name using ng-model directive
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
Step 4: Bind the value of above model defined using ng-bind directive
<p>Hello <span ng-bind = "name"></span>!</p>
Executing AngularJS Application
Use the above-mentioned three steps in an HTML page.
testAngularJS.htm
<html>
<head>
<title>AngularJS First Application</title>
</head>
<body>
<h1>Sample Application</h1>

<div ng-app = "">


<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
</div>

<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">


</script>

</body>
</html>

Output
Open the file testAngularJS.htm in a web browser. Enter your name and see the
result.

Sample Application

Enter your Name:

Hello !

You might also like