FSD Material

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

REACT BASICS

Full stack development


What is full stack development?
Full stack development: It refers to the development of both front end(client side)
and back end(server side) portions of web application.
Full stack web Developers: Full stack web developers have the ability to design complete
web applications and websites. They work on the frontend, backend, database and debugging
of web applications or websites.

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

The main components of a full stack development are the front-end, back-end and database

What is a Tech Stack?

A tech stack is the combination of technologies a company uses to build and run an application
or project. Sometimes called a “solutions stack,” a tech stack typically consists of programming
languages, frameworks, a database, front-end tools, back-end tools, and applications connected
via APIs.

Example tech stack for a web application

Most tech stacks are a combination of frontend and backend technologies like JavaScript (user
interface), Python (programming language), MongoDB (database), and Apache (server).

What is an example of a tech stack?

One of the most popular and easiest examples of a technology stack is the MEAN stack. MEAN
stands for MongoDB-Express-Angular-Node.js. You can replace Angular and use React, as in
the MERN stack, since React is becoming equally popular, especially for single page web
applications.

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

MEAN stack components

In the above diagram, Node.js is the runtime for the web applications, Angular provides the
user interface, Express is a web framework built over Node.js, and MongoDB is the data
platform or data stack that has the ability to transform data into a more usable form.

The MEAN and MERN stacks are trending tech stacks for web development. Many full-stack
developers find these stacks easy to learn and implement because of the common technology
used throughout the stack: JavaScript.

In general, a tech stack can be a frontend tech stack, backend tech stack, or a mix of both—i.e.,
a full stack.

What is the MERN stack?

MERN stands for MongoDB, Express, React, Node, after the four key technologies that make
up the stack.

 MongoDB — document database


 Express(.js) — Node.js web framework

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

 React(.js) — a client-side JavaScript framework


 Node(.js) — the premier JavaScript web server

Express and Node make up the middle (application) tier. Express.js is a server-side web
framework, and Node.js is the popular and powerful JavaScript server platform. Regardless of
which variant you choose, ME(RVA)N is the ideal approach to working with JavaScript and
JSON, all the way through.

How does the MERN stack work?

The MERN architecture allows you to easily construct a three-tier architecture (front end, back
end, database) entirely using JavaScript and JSON.

React.js front end

The top tier of the MERN stack is React.js, the declarative JavaScript framework for creating
dynamic client-side applications in HTML. React lets you build up complex interfaces through
simple components, connect them to data on your back-end server, and render them as HTML.

React’s strong suit is handling stateful, data-driven interfaces with minimal code and minimal
pain, and it has all the bells and whistles you’d expect from a modern web framework: great
support for forms, error handling, events, lists, and more.

Express.js and Node.js server tier

The next level down is the Express.js server-side framework, running inside a Node.js server.
Express.js bills itself as a “fast, unopinionated, minimalist web framework for Node.js,” and

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

that is indeed exactly what it is. Express.js has powerful models for URL routing (matching an
incoming URL with a server function), and handling HTTP requests and responses.

By making XML HTTP Requests (XHRs) or GETs or POSTs from your React.js front end,
you can connect to Express.js functions that power your application. Those functions, in turn,
use MongoDB’s Node.js drivers, either via callbacks or using promises, to access and update
data in your MongoDB database.

MongoDB database tier

If your application stores any data (user profiles, content, comments, uploads, events, etc.),
then you’re going to want a database that’s just as easy to work with as React, Express, and
Node.

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.

UNIT-1
REACT BASICS
1.1.Introduction
ReactJS is a declarative, efficient, and flexible JavaScript library for building reusable UI
components. It is an open-source, component-based front end library responsible only for the
view layer of the application. It was created by Jordan Walke, who was a software engineer at
Facebook. It was initially developed and maintained by Facebook and was later used in its
products like WhatsApp & Instagram. Facebook developed ReactJS in 2011 in its newsfeed
section, but it was released to the public in the month of May 2013.

Today, most of the websites are built using MVC (model view controller) architecture. In MVC
architecture, React is the 'V' which stands for view, whereas the architecture is provided by the
Redux or Flux.

A ReactJS application is made up of multiple components, each component responsible for


outputting a small, reusable piece of HTML code. The components are the heart of all React
applications. These Components can be nested with other components to allow complex
applications to be built of simple building blocks. ReactJS uses virtual DOM based mechanism
to fill data in HTML DOM. The virtual DOM works fast as it only changes individual DOM
elements instead of reloading complete DOM every time.

To create React app, we write React components that correspond to various elements. We
organize these components inside higher level components which define the application
structure. For example, we take a form that consists of many elements like input fields, labels,
or buttons. We can write each element of the form as React components, and then we combine

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

it into a higher-level component, i.e., the form component itself. The form components would
specify the structure of the form along with elements inside of it.

Why learn ReactJS?


Today, many JavaScript frameworks are available in the market(like angular, node), but still,
React came into the market and gained popularity amongst them. The previous frameworks
follow the traditional data flow structure, which uses the DOM (Document Object Model).
DOM is an object which is created by the browser each time a web page is loaded. It
dynamically adds or removes the data at the back end and when any modifications were done,
then each time a new DOM is created for the same page. This repeated creation of DOM makes
unnecessary memory wastage and reduces the performance of the application.

Therefore, a new technology ReactJS framework invented which remove this drawback.
ReactJS allows you to divide your entire application into various components. ReactJS still
used the same traditional data flow, but it is not directly operating on the browser's Document
Object Model (DOM) immediately; instead, it operates on a virtual DOM. It means rather than
manipulating the document in a browser after changes to our data, it resolves changes on a
DOM built and run entirely in memory. After the virtual DOM has been updated, React
determines what changes made to the actual browser's DOM. The React Virtual DOM exists
entirely in memory and is a representation of the web browser's DOM. Due to this, when we
write a React component, we did not write directly to the DOM; instead, we are writing virtual
components that react will turn into the DOM.

1.2.React Components:
Earlier, the developers write more than thousands of lines of code for developing a single page
application. These applications follow the traditional DOM structure, and making changes in
them was a very challenging task. If any mistake found, it manually searches the entire
application and update accordingly. The component-based approach was introduced to
overcome an issue. In this approach, the entire application is divided into a small logical group
of code, which is known as components.
A Component is considered as the core building blocks of a React application. It makes the
task of building UIs much easier. Each component exists in the same space, but they work
independently from one another and merge all in a parent component, which will be the final
UI of your application.
Every React component have their own structure, methods as well as APIs. They can be
reusable as per your need. For better understanding, consider the entire UI as a tree. Here, the
root is the starting component, and each of the other pieces becomes branches, which are further
divided into sub-branches.

React Components

In ReactJS, we have mainly two types of components. They are

1. Functional Components
2. Class Components
Functional Components:
In React, function components are a way to write components that only contain a render method
and don't have their own state. They are simply JavaScript functions that may or may not

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

receive data as parameters. We can create a function that takes props(properties) as input and
returns what should be rendered. A valid functional component can be shown in the below
example.

function WelcomeMessage(props) {
return <h1>Welcome to the , {props.name}</h1>;
}
The functional component is also known as a stateless component because they do not hold or
manage state. It can be explained in the below example.

Class Components:
Class components are more complex than functional components. It requires you to extend
from React. Component and create a render function which returns a React element. You can
pass data from one class to other class components. You can create a class by defining a class
that extends Component and has a render function. Valid class component is shown in the
below example.

class MyComponent extends React.Component {


render() {
return (
<div>This is main component.</div>
);
}
}
The class component is also known as a stateful component because they can hold or manage
local state. It can be explained in the below example.

Example
In this example, we are creating the list of unordered elements, where we will dynamically
insert StudentName for every object from the data array. Here, we are using ES6 arrow syntax
(=>) which looks much cleaner than the old JavaScript syntax. It helps us to create our elements
with fewer lines of code. It is especially useful when we need to create a list with a lot of items.

import React, { Component } from 'react';


class App extends React.Component {
constructor() {
super();
this.state = {
data:
[
{
"name":"Abhishek"
},
{
"name":"Saharsh"
},
{
"name":"Ajay"
}

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

]
}
}
render() {
return (
<div>
<StudentName/>
<ul>
{this.state.data.map((item) => <List data = {item} />)}
</ul>
</div>
);
}
}
class StudentName extends React.Component {
render() {
return (
<div>
<h1>Student Name Detail</h1>
</div>
);
}
}
class List extends React.Component {
render() {
return (
<ul>
<li>{this.props.data.name}</li>
</ul>
);
}
}
export default App;

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

1.3.React Nesting Components

In React, we can nest components inside within one another. This helps in creating more
complex User Interfaces. The components that are nested inside parent components are called
child components. Import and Export keywords facilitate nesting of the components.

 Export - This keyword is used to export a particular module or file and use it in another
module.

 Import - This keyword is used to import a particular module or file and use it in the existing
module.

Importing named values allows the user to import multiple objects from a file.

1.4.React Props:
Props stand for "Properties." They are read-only components. It is an object which stores the
value of attributes of a tag and work similar to the HTML attributes. It gives a way to pass data
from one component to other components. It is similar to function arguments. Props are passed
to the component in the same way as arguments passed in a function.

Props are immutable so we cannot modify the props from inside the component. Inside the
components, we can add attributes called props. These attributes are available in the component
as this.props and can be used to render dynamic data in our render method.

When you need immutable data in the component, you have to add props to reactDom.render()
method in the main.js file of your ReactJS project and used it inside the component in which
you need. It can be explained in the below example.

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

Example
App.js

import React, { Component } from 'react';


class App extends React.Component {
render() {
return (
<div>
<h1> Welcome to { this.props.name } </h1>
<p> <h4> Skyeagle is one of the best Java training institute in Noida, Delhi,
Gurugram, Ghaziabad and Faridabad. </h4> </p>
</div>
);
}
}
export default App;
Main.js

import React from 'react';


import ReactDOM from 'react-dom';
import App from './App.js';

ReactDOM.render(<App name = "Skyeagle!!" />, document.getElementById('app'));

Default Props:
It is not necessary to always add props in the reactDom.render() element. You can also set
default props directly on the component constructor. It can be explained in the below
example.

Example
App.js

import React, { Component } from 'react';


class App extends React.Component {
render() {
return (
<div>
<h1>Default Props Example</h1>

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

<h3>Welcome to {this.props.name}</h3>
<p>Skyeagle is one of the best Java training institute in Noida, Delhi, Gurugram,
Ghaziabad and Faridabad.</p>
</div>
);
}
}
App.defaultProps = {
name: "Skyeagle"
}
export default App;
Main.js

import React from 'react';


import ReactDOM from 'react-dom';
import App from './App.js';

ReactDOM.render(<App/>, document.getElementById('app'));

1.5.React State
The state is an updatable structure that is used to contain data or information about the
component. The state in a component can change over time. The change in state over time can
happen as a response to user action or system event. A component with the state is known as
stateful components. It is the heart of the react component which determines the behavior of
the component and how it will render. They are also responsible for making a component
dynamic and interactive.

A state must be kept as simple as possible. It can be set by using the setState() method and
calling setState() method triggers UI updates. A state represents the component's local state or
information. It can only be accessed or modified inside the component or by the component
directly. To set an initial state before any interaction occurs, we need to use the getInitialState()
method.

For example, if we have five components that need data or information from the state, then we
need to create one container component that will keep the state for all of them.

Defining State
To define a state, you have to first declare a default set of values for defining the component's
initial state. To do this, add a class constructor which assigns an initial state using this.state.
The 'this.state' property can be rendered inside render() method.

Example
The below sample code shows how we can create a stateful component using ES6 syntax.

import React, { Component } from 'react';


class App extends React.Component {
constructor() {

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

super();
this.state = { displayBio: true };
}
render() {
const bio = this.state.displayBio ? (
<div>
<p><h3>Skyeagle is one of the best Java training institute in Noida, Delhi,
Gurugram, Ghaziabad and Faridabad. We have a team of experienced Java developers and
trainers from multinational companies to teach our campus students.</h3></p>
</div>
) : null;
return (
<div>
<h1> Welcome to </h1>
{ bio }
</div>
);
}
}
export default App;
To set the state, it is required to call the super() method in the constructor. It is because
this.state is uninitialized before the super() method has been called.

Changing the State


We can change the component state by using the setState() method and passing a new state
object as the argument. Now, create a new method toggleDisplayBio() in the above example
and bind this keyword to the toggleDisplayBio() method otherwise we can't access this inside
toggleDisplayBio() method.

this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
Example
In this example, we are going to add a button to the render() method. Clicking on this button
triggers the toggleDisplayBio() method which displays the desired output.

import React, { Component } from 'react';


class App extends React.Component {
constructor() {

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

super();
this.state = { displayBio: false };
console.log('Component this', this);
this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
}
toggleDisplayBio(){
this.setState({displayBio: !this.state.displayBio});
}
render() {
return (
<div>
<h1>Welcome to </h1>
{
this.state.displayBio ? (
<div>
<p><h4>Skyeagle is one of the best Java training institute in Noida, Delhi,
Gurugram, Ghaziabad and Faridabad. We have a team of experienced Java developers and
trainers from multinational companies to teach our campus students.</h4></p>
<button onClick={this.toggleDisplayBio}> Show Less </button>
</div>
):(
<div>
<button onClick={this.toggleDisplayBio}> Read More </button>
</div>
)
}
</div>
)
}
}
export default App;

When you click the Read More button, you will get the below output, and when you click the
Show Less button, you will get the output as shown in the above image.

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

1.6.React JSX
As we have already seen that, all of the React components have a render function. The render
function specifies the HTML output of a React component. JSX(JavaScript Extension), is a
React extension which allows writing JavaScript code that looks like HTML. In other words,
JSX is an HTML-like syntax used by React that extends ECMAScript so that HTML-like
syntax can co-exist with JavaScript/React code. The syntax is used by preprocessors (i.e.,
transpilers like babel) to transform HTML-like syntax into standard JavaScript objects that a
JavaScript engine will parse.

JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree structures) in the
same file where you write JavaScript code, then preprocessor will transform these expressions
into actual JavaScript code. Just like XML/HTML, JSX tags have a tag name, attributes, and
children.

Example

Here, we will write JSX syntax in JSX file and see the corresponding JavaScript code which
transforms by preprocessor(babel).

JSX File

<div>Hello Skyeagle</div>
Corresponding Output

React.createElement("div", null, "Hello Skyeagle");


The above line creates a react element and passing three arguments inside where the first is the
name of the element which is div, second is the attributes passed in the div tag, and last is the
content you pass which is the "Hello Skyeagle."

Why use JSX?


It is faster than regular JavaScript because it performs optimization while translating the code
to JavaScript.
Instead of separating technologies by putting markup and logic in separate files, React uses
components that contain both. We will learn components in a further section.
It is type-safe, and most of the errors can be found at compilation time.
It makes easier to create templates.

Nested Elements in JSX


To use more than one element, you need to wrap it with one container element. Here, we use
div as a container element which has three nested elements inside it.

App.JSX

import React, { Component } from 'react';

class App extends Component{

render(){

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

return(

<div>

<h1>Skyeagle</h1>

<h2>Training Institutes</h2>

<p>This website contains the best CS tutorials.</p>

</div>

);

export default App;

JSX Attributes
JSX use attributes with the HTML elements same as regular HTML. JSX uses camelcase
naming convention for attributes rather than standard naming convention of HTML such as a
class in HTML becomes className in JSX because the class is the reserved keyword in
JavaScript. We can also use our own custom attributes in JSX. For custom attributes, we need
to use data- prefix. In the below example, we have used a custom attribute data-demoAttribute
as an attribute for the <p> tag.

Example
import React, { Component } from 'react';

class App extends Component{

render(){

return(

<div>

<h1>Skyeagle</h1>

<h2>Training Institutes</h2>

<p data-demoAttribute = "demo">This website contains the best CS tutorials.</p>

</div>

);

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

export default App;


In JSX, we can specify attribute values in two ways:

1. As String Literals: We can specify the values of attributes in double quotes:

var element = <h2 className = "firstAttribute">Hello Skyeagle</h2>;


Example

import React, { Component } from 'react';

class App extends Component{

render(){

return(

<div>

<h1 className = "hello" >Skyeagle</h1>

<p data-demoAttribute = "demo">This website contains the best CS tutorials.</p>


</div>
);

export default App;


Output:

Skyeagle
This website contains the best CS tutorials.
2. As Expressions: We can specify the values of attributes as expressions using curly braces
{}:

var element = <h2 className = {varName}>Hello Skyeagle</h2>;


Example

import React, { Component } from 'react';

class App extends Component{


render(){
return(
<div>

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

<h1 className = "hello" >{25+20}</h1>


</div>
);
}
}
export default App;
Output:
45
JSX Comments
JSX allows us to use comments that begin with /* and ends with */ and wrapping them in
curly braces {} just like in the case of JSX expressions. Below example shows how to use
comments in JSX.
Example
import React, { Component } from 'react';
class App extends Component{
render(){
return(
<div>
<h1 className = "hello" >Hello Skyeagle</h1>
{/* This is a comment in JSX */}
</div>
);
}
}

export default App;

JSX Styling
React always recommends to use inline styles. To set inline styles, you need to use
camelCase syntax. React automatically allows appending px after the number value on
specific elements. The following example shows how to use styling in the element.

Example
import React, { Component } from 'react';

class App extends Component{

render(){
var myStyle = {

fontSize: 80,
fontFamily: 'Courier',
color: '#003300'

}
return (

<div>
<h1 style = {myStyle}>www.Skyeagle.com</h1>
</div>

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

);
}
}
export default App;

1.7.Component Life-Cycle
In ReactJS, every component creation process involves various lifecycle methods. These
lifecycle methods are termed as component's lifecycle. These lifecycle methods are not very
complicated and called at various points during a component's life. The lifecycle of the
component is divided into four phases. They are:

Initial Phase
Mounting Phase
Updating Phase
Unmounting Phase
Each phase contains some lifecycle methods that are specific to the particular phase. Let us
discuss each of these phases one by one.

1. Initial Phase
It is the birth phase of the lifecycle of a ReactJS component. Here, the component starts its
journey on a way to the DOM. In this phase, a component contains the default Props and initial
State. These default properties are done in the constructor of a component. The initial phase
only occurs once and consists of the following methods.

getDefaultProps()
It is used to specify the default value of this.props. It is invoked before the creation of the
component or any props from the parent is passed into it.
getInitialState()
It is used to specify the default value of this.state. It is invoked before the creation of the
component.

2. Mounting Phase
In this phase, the instance of a component is created and inserted into the DOM. It consists of
the following methods.

componentWillMount()
This is invoked immediately before a component gets rendered into the DOM. In the case,
when you call setState() inside this method, the component will not re-render.
componentDidMount()
This is invoked immediately after a component gets rendered and placed on the DOM. Now,
you can do any DOM querying operations.
render()
This method is defined in each and every component. It is responsible for returning a single
root HTML node element. If you don't want to render anything, you can return a null or false
value.

3. Updating Phase

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

It is the next phase of the lifecycle of a react component. Here, we get new Props and change
State. This phase also allows to handle user interaction and provide communication with the
components hierarchy. The main aim of this phase is to ensure that the component is displaying
the latest version of itself. Unlike the Birth or Death phase, this phase repeats again and again.
This phase consists of the following methods.

componentWillRecieveProps()
It is invoked when a component receives new props. If you want to update the state in response
to prop changes, you should compare this.props and nextProps to perform state transition by
using this.setState() method.
shouldComponentUpdate()
It is invoked when a component decides any changes/updation to the DOM. It allows you to
control the component's behavior of updating itself. If this method returns true, the component
will update. Otherwise, the component will skip the updating.
componentWillUpdate()
It is invoked just before the component updating occurs. Here, you can't change the component
state by invoking this.setState() method. It will not be called, if shouldComponentUpdate()
returns false.
render()
It is invoked to examine this.props and this.state and return one of the following types: React
elements, Arrays and fragments, Booleans or null, String and Number. If
shouldComponentUpdate() returns false, the code inside render() will be invoked again to
ensure that the component displays itself properly.
componentDidUpdate()
It is invoked immediately after the component updating occurs. In this method, you can put
any code inside this which you want to execute once the updating occurs. This method is not
invoked for the initial render.
4. Unmounting Phase
It is the final phase of the react component lifecycle. It is called when a component instance is
destroyed and unmounted from the DOM. This phase contains only one method and is given
below.

componentWillUnmount()
This method is invoked immediately before a component is destroyed and unmounted
permanently. It performs any necessary cleanup related task such as invalidating timers, event
listener, canceling network requests, or cleaning up DOM elements. If a component instance
is unmounted, you cannot mount it again.
Example
import React, { Component } from 'react';

class App extends React.Component {


constructor(props) {
super(props);
this.state = {hello: "Skyeagle"};
this.changeState = this.changeState.bind(this)
}
render() {
return (
<div>
<h1>ReactJS components Lifecycle</h1>

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

<h3>Hello {this.state.hello}</h3>
<button onClick = {this.changeState}>Click Here!</button>
</div>
);
}
componentWillMount() {
console.log('Component Will MOUNT!')
}
componentDidMount() {
console.log('Component Did MOUNT!')
}
changeState(){
this.setState({hello:"All!!- Its a great reactjs tutorial."});
}
componentWillReceiveProps(newProps) {
console.log('Component Will Recieve Props!')
}
shouldComponentUpdate(newProps, newState) {
return true;
}
componentWillUpdate(nextProps, nextState) {
console.log('Component Will UPDATE!');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component Did UPDATE!')
}
componentWillUnmount() {
console.log('Component Will UNMOUNT!')
}
}
export default App;

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT BASICS

K.SONI SHARMILA,DEPT.OF CSE,SVECW


REACT ADVANCED CONCEPTS

UNIT-2
REACT ADVANCED CONCEPTS
2.1.React Events:
An event is an action that could be triggered as a result of the user action or system generated
event. For example, a mouse click, loading of a web page, pressing a key, window resizes, and
other interactions are called events.

React has its own event handling system which is very similar to handling events on DOM
elements. The react event handling system is known as Synthetic Events. The synthetic event
is a cross-browser wrapper of the browser's native event.

React Events

Handling events with react have some syntactic differences from handling events on DOM.
These are:
React events are named as camelCase instead of lowercase.
With JSX, a function is passed as the event handler instead of a string. For example:
Event declaration in plain HTML:

<button onclick="showMessage()">
Hello Skyeagle
</button>
Event declaration in React:
<button onClick={showMessage}>
Hello Skyeagle
</button>
3. In react, we cannot return false to prevent the default behavior. We must call
preventDefault event explicitly to prevent the default behavior. For example:

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

In plain HTML, to prevent the default link behavior of opening a new page, we can write:
<a href="#" onclick="console.log('You had clicked a Link.'); return false">
Click_Me
</a>
In React, we can write it as:
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('You had clicked a Link.');
}
return (
<a href="#" onClick={handleClick}>
Click_Me
</a>
);
}
In the above example, e is a Synthetic Event which defines according to the W3C spec.
Now let us see how to use Event in React.
Example
In the below example, we have used only one component and adding an onChange event.
This event will trigger the changeText function, which returns the company name.

import React, { Component } from 'react';


class App extends React.Component {
constructor(props) {
super(props);
this.state = {
companyName: ''
};
}
changeText(event) {
this.setState({
companyName: event.target.value
});
}
render() {
return (
<div>
<h2>Simple Event Example</h2>
<label htmlFor="name">Enter company name: </label>
<input type="text" id="companyName" onChange={this.changeText.bind(this)}/>
<h4>You entered: { this.state.companyName }</h4>
</div>
);
}
}
export default App;
Output

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

When you execute the above code, you will get the following output.

2.2.React Forms
Forms are an integral part of any modern web application. It allows the users to interact with
the application as well as gather information from the users. Forms can perform many tasks
that depend on the nature of your business requirements and logic such as authentication of the
user, adding user, searching, filtering, booking, ordering, etc. A form can contain text fields,
buttons, checkbox, radio button, etc.

Creating Form
React offers a stateful, reactive approach to build a form. The component rather than the DOM
usually handles the React form. In React, the form is usually implemented by using controlled
components.
There are mainly two types of form input in React.
Uncontrolled component
Controlled component
Uncontrolled component:
The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles
the form data. Here, the HTML elements maintain their own state that will be updated when
the input value changes. To write an uncontrolled component, you need to use a ref to get form
values from the DOM. In other words, there is no need to write an event handler for every state
update. You can use a ref to access the input field value of the form from the DOM.
Example
In this example, the code accepts a field username and company name in an uncontrolled
component.

import React, { Component } from 'react';


class App extends React.Component {
constructor(props) {
super(props);
this.updateSubmit = this.updateSubmit.bind(this);
this.input = React.createRef();
}
updateSubmit(event) {
alert('You have entered the UserName and CompanyName successfully.');
event.preventDefault();
}

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

render() {
return (
<form onSubmit={this.updateSubmit}>
<h1>Uncontrolled Form Example</h1>
<label>Name:
<input type="text" ref={this.input} />
</label>
<label>
CompanyName:
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;

Controlled Component
In HTML, form elements typically maintain their own state and update it according to the user
input. In the controlled component, the input form element is handled by the component rather
than the DOM. Here, the mutable state is kept in the state property and will be updated only
with setState() method.
Controlled components have functions that govern the data passing into them on every
onChange event, rather than grabbing the data only once, e.g., when you click a submit button.
This data is then saved to state and updated with setState() method. This makes component
have better control over the form elements and data.
A controlled component takes its current value through props and notifies the changes through
callbacks like an onChange event. A parent component "controls" this changes by handling the
callback and managing its own state and then passing the new values as props to the controlled
component. It is also called as a "dumb component."
Example

import React, { Component } from 'react';


class App extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('You have submitted the input successfully: ' + this.state.value);
event.preventDefault();
}
render() {

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

return (
<form onSubmit={this.handleSubmit}>
<h1>Controlled Form Example</h1>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;
Output
When you execute the above code, you will see the following screen.

Handling Multiple Inputs in Controlled Component


If you want to handle multiple controlled input elements, add a name attribute to each element,
and then the handler function decided what to do based on the value of event.target.name.

Example
import React, { Component } from 'react';
class App extends React.Component {

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

constructor(props) {
super(props);
this.state = {
personGoing: true,
numberOfPersons: 5
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return (
<form>
<h1>Multiple Input Controlled Form Example</h1>
<label>
Is Person going:
<input
name="personGoing"
type="checkbox"
checked={this.state.personGoing}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Number of persons:
<input
name="numberOfPersons"
type="number"
value={this.state.numberOfPersons}
onChange={this.handleInputChange} />
</label>
</form>
);
}
}
export default App;

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

2.3.Scaling React components:

1. Setting default properties for components


2. Understanding React property types and validation
3. Rendering children
4. Creating higher-order components for code reuse
5. Presentational versus container components
1. Setting Default properties in components

Imagine that you’re building a Datepicker component that takes a few required properties

such as number of rows, locale, and current date:

<Datepicker currentDate={Date()} locale="US" rows={4}/>


The key benefit of defaultProps is that if a property is missing, a default value is rendered.
To set a default property value on the component class, you define defaultProps . For example,
in the aforementioned Datepicker component definition, you can add a static class attribute

(not an instance attribute, because that won’t work—instance attributes are set
in constructor() ):

class Datepicker extends React.Component {


...
}
Datepicker.defaultProps = {
currentDate: Date(),
rows: 4,
locale: 'US'
}

class Button extends React.Component {


render() {
return <button className="btn" >{this.props.buttonLabel}</button>
}
}

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

Button.defaultProps = {buttonLabel: 'Submit'}

class Content extends React.Component {


render() {
return (
<div>
<Button buttonLabel="Start"/>
<Button />
<Button />
<Button />
</div>
)
}
}

2. React property types and validation

Going back to the earlier example with the Datepicker component and coworkers who aren’t
aware of property types ( "5" versus 5 ), you can set property types to use with React.js
component classes. You do so via the propTypes static attribute. This feature of property types

doesn’t enforce data types on property values and instead gives you a warning. That is, if you’re
in development mode, and a type doesn’t match, you’ll get a warning message in the console

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

and in production; nothing will be done to prevent the wrong type from being used. In essence,
React.js suppresses this warning in production mode. Thus, propTypes is mostly a

convenience feature to warn you about mismatches in data types at a developmental stage.

3. Rendering children

Let’s continue with the fictional React project; but instead of a Datepicker (which is now

robust and warns you about any missing or incorrect properties), you’re tasked with creating a
component that’s universal enough to use with any children you pass to it. It’s a blog
post Content component that may consist of a heading and a paragraph of text:

<Content>

<h1>React.js</h1>

<p>Rocks</p>

</Content>

The children property is an easy way to render all children with {this.props.children} . You
can also do more than rendering. For example, add a <div> and pass along child elements:

class Content extends React.Component {

render() {

return (

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

<div className="content">

{this.props.children}

</div>

The parent of Content has the children <h1> and <p> :

ReactDOM.render(

<div>

<Content>

<h1>React</h1>

<p>Rocks</p>

</Content>

</div>,

document.getElementById('content')

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

4.Creating React higher-order components for code reuse

A higher-order component (HOC) lets you enhance a component with additional logic You can
think of this pattern as components inheriting functionality when used with HOCs. In other
words, HOCs let you reuse code. This allows you and your team to share functionality among
React.js components.

Simplified representation of the higher-order com

5. Presentational versus container components:


Presentational components typically only add structure to DOM and styling. They take
properties but often don’t have their own states. Most of the time, you can use functions for
stateless presentational components.

2.4.REACT ROUTING:
React Router is a standard library for routing in React. It enables the navigation among
views of various components in a React Application, allows changing the browser URL,
and keeps the UI in sync with the URL.
Let us create a simple application to React to understand how the React Router works. The
application will contain three components: home component, about a component, and
contact component. We will use React Router to navigate between these components.
After installing react-router-dom, add its components to your React application.

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

Adding React Router Components: The main Components of React Router are:
 BrowserRouter: BrowserRouter is a router implementation that uses the HTML5
history API(pushState, replaceState and the popstate event) to keep your UI in sync
with the URL. It is the parent component that is used to store all of the other
components.
 Routes: It’s a new component introduced in the v6 and a upgrade of the component.
The main advantages of Routes over Switch are:
 Relative s and s
 Routes are chosen based on the best match instead of being traversed in
order.
 Route: Route is the conditionally shown component that renders some UI when its path
matches the current URL.
 Link: Link component is used to create links to different routes and implement
navigation around the application. It works like HTML anchor tag.
Using React Router: To use React Router, let us first create few components in the react
application. In your project directory, create a folder named component inside the src folder
and now add 3 files named home.js, about.js and contact.js to the component folder.
Let us add some code to our 3 components:
Home.js
import React from 'react';

function Home (){


return <h1>Welcome to the world of Geeks!</h1>
}

export default Home;


About.js
import React from 'react';

function About () {
return <div>
<h2>shri Vishnu engineering college for women</h2>

Read more about us at :


<a href="https://www.svecw.edu.in/about/">
</a>
</div>
}
export default About;
Contact.js
import React from 'react';

function Contact (){


return <address>
You can find us here:<br />
SVECW<br />
VISHNUPUR,BHIMAVARAM <br />
PIN-534201
</address>

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

export default Contact;


BrowserRouter: Add BrowserRouter aliased as Router to your app.js file in order to wrap
all the other components. BrowserRouter is a parent component and can have only single
child.
class App extends Component {
render() {
return (
<Router>
<div className="App">
</div>
</Router>
);
}
}
Link: Let us now create links to our components. Link component uses the to prop to
describe the location where the links should navigate to.
<div className="App">
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About Us</Link>
</li>
<li>
<Link to="/contact">Contact Us</Link>
</li>
</ul>
</div>
Route: Route component will now help us to establish the link between component’s UI and
the URL. To include routes to the application, add the code give below to your app.js.
<Route exact path='/' element={< Home />}></Route>
<Route exact path='/about' element={< About />}></Route>
<Route exact path='/contact' element={< Contact />}></Route>
Routes: To render a single component, wrap all the routes inside the Routes Component.
<Routes>
<Route exact path='/' element={< Home />}></Route>
<Route exact path='/about' element={< About />}></Route>
<Route exact path='/contact' element={< Contact />}></Route>
</Routes>
After adding all the components here is our complete source code:
import React, { Component } from 'react';
import { BrowserRouter as Router,Routes, Route, Link } from 'react-router-dom';
import Home from './component/home';
import About from './component/about';
import Contact from './component/contact';
import './App.css';

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

class App extends Component {


render() {
return (
<Router>
<div className="App">
<ul className="App-header">
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About Us</Link>
</li>
<li>
<Link to="/contact">Contact Us</Link>
</li>
</ul>
<Routes>
<Route exact path='/' element={< Home />}></Route>
<Route exact path='/about' element={< About />}></Route>
<Route exact path='/contact' element={< Contact />}></Route>
</Routes>
</div>
</Router>
);
}
}

export default App;

2.5.REDUX:
What is Redux?
Redux is a predictable state container designed to help you write JavaScript apps that behave
consistently across client, server, and native environments, and are easy to test.

With Redux, the state of your application is kept in a store, and each component can access
any state that it needs from this store.

What is Redux used for?


Simply put, Redux is used to maintain and update data across your applications for multiple
components to share, all while remaining independent of the components.

Without Redux, you would have to make data dependent on the components and pass it
through different components to where it’s needed.

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

WITHOUT REDUX
In our example above, we only need some data in the parent and inner child components, but
we’re forced to pass it to all the components (including the child component that doesn’t need
it) to get it to where it’s needed.

With Redux, we can make state data independent of the components, and when needed, a
component can access or update through the Redux store.

WITH REDUX
What is state management in Redux?
State management is essentially a way to facilitate communication and sharing of data across
components. It creates a tangible data structure to represent the state of your app that you can
read from and write to. That way, you can see otherwise invisible states while you’re working
with them.

Most libraries, such as React, Angular, etc. are built with a way for components to internally
manage their state without any need for an external library or tool. It does well for applications
with few components, but as the application grows bigger, managing states shared across
components becomes a chore.

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

In an app where data is shared among components, it might be confusing to actually know
where a state should live. Ideally, the data in a component should live in just one component,
so sharing data among sibling components becomes difficult.

For instance, in React, to share data among siblings, a state has to live in the parent component.
A method for updating this state is provided by the parent component and passed as props to
these sibling components.

Here’s a simple example of a login component in React. The input of the login component
affects what is displayed by its sibling component, the status component:

class App extends React.Component {


constructor(props) {
super(props);
// First the Parent creates a state for what will be passed
this.state = { userStatus: "NOT LOGGED IN"}
this.setStatus = this.setStatus.bind(this);
}
// A method is provided for the child component to update the
state of the
// userStatus
setStatus(username, password) {
const newUsers = users;
newUsers.map(user => {
if (user.username == username && user.password === password) {
this.setState({
userStatus: "LOGGED IN"
})
}
});
}

render() {
return (
<div>
// the state is passed to the sibling as a props as is
updated whenever
// the child component changes the input
<Status status={this.state.userStatus} />
// this method is passed to the child component as a props
which it
// uses to change the state of the userStatus
<Login handleSubmit={this.setStatus} />
</div>
);
}
});
Basically, the state will have to be lifted up to the nearest parent component and to the next
until it gets to an ancestor that is common to both components that need the state, and then it

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

is passed down. This makes the state difficult to maintain and less predictable. It also means
passing data to components that do not need it.

It’s clear that state management gets messy as the app gets complex. This is why you need a
state management tool like Redux that makes it easier to maintain these states. Let’s get a good
overview of Redux concepts before considering its benefits.

What are Redux actions?


Simply put, Redux actions are events.

They are the only way you can send data from your application to your Redux store. The data
can be from user interactions, API calls, or even form submissions.

Actions are plain JavaScript objects that must have

 a type property to indicate the type of action to be carried out, and


 a payload object that contains the information that should be used to change the state.

{
type: "LOGIN",
payload: {
username: "foo",
password: "bar"
}
}
What are Redux reducers?
Reducers are pure functions that take the current state of an application, perform an action,
and return a new state. The reducer handles how the state (application data) will change in
response to an action.

const LoginComponent = (state = initialState, action) => {


switch (action.type) {

// This reducer handles any action with type "LOGIN"


case "LOGIN":
return state.map(user => {
if (user.username !== action.username) {
return user;
}

if (user.password == action.password) {
return {
...user,
login_status: "LOGGED IN"
}
}
});
default:
return state;

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

} };
What is Redux Store?
The store is a “container” (really a JavaScript object) that holds the application state, and the
only way the state can change is through actions dispatched to the store. Redux allows
individual components connect to the store and apply changes to it by dispatching actions.

It is highly recommended to keep only one store in any Redux application. You can access
the state stored, update the state, and register or unregister listeners via helper methods.

Let’s create a store for our login app:

const store = createStore(LoginComponent);


Why use Redux?
1. Redux makes the state predictable
2. Redux is maintainable
3. Debugging is easy in Redux
4. Performance benefits
5. Ease of testing
6. State persistence
7. Server-side rendering

2.6.Unit Testing of React Apps using JEST:


Testing software is as important as developing it, since, testing helps find out whether the
software meets the actual requirements or not. A thoroughly tested software product ensures
dependability, security, and high performance, which leads to time-saving, customer
satisfaction, and cost-effectiveness.
ReactJS is a popular JavaScript library that is used for building highly rich user interfaces
A few reasons that make React a popular framework among developers are:

 Ease of Learning: React JS has a short learning curve as compared to other front-end
libraries or frameworks, hence any developer with a basic knowledge of JavaScript can start
learning and building apps using React JS in a short period of time.
 Quick Rendering: React JS uses virtual DOM and algorithms like diffing, which makes the
development process fast and efficient.
 One-way data-binding: React JS follows one-way data binding, which means you get more
control over the flow of the application.
 High Performance: The best advantage of React JS is its performance. There are many
features that make it possible:
o React uses virtual DOM, which enables the re-rendering of nodes only when they are
required to.

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

o React JS also supports bundling and tree shaking, which minimizes the end user’s resource
load.
This tutorial deep dives into performing unit testing of React Apps using JEST.

What is Unit Testing for React Apps? Why is it important?


Unit Testing is a testing method that tests an individual unit of software in isolation. Unit
testing for React Apps means testing an individual React Component.
“Unit testing is a great discipline, which can lead to 40% – 80% reductions in bug density.” –
Unit Testing is important for React Apps, as it helps in testing the individual functionality of
React components. Moreover, any error in code can be identified at the beginning itself,
saving time to rectify it at later stages. Some of the core benefits of Unit Testing are:

 Process Becomes Agile: Agile Testing process is the main advantage of unit testing. When
you add more features to the software, it might affect the older designs and you might need to
make changes to the old design and code later. This can be expensive and require extra effort.
But if you do unit testing, the whole process becomes much faster and easier.
 Quality of code: Unit testing significantly improves the quality of the code. It helps
developers to identify the smallest defects that can be present in the units before they go for
the integration testing.
 Facilitates change: Refactoring the code or updating the system library becomes much easier
when you test each component of the app individually.
 Smooth Debugging: The debugging process is very simplified by doing unit testing. If a
certain test fails, then only the latest changes that have been made to the code need to be
debugged.
 Reduction in cost: When bugs are detected at an early stage, through unit testing, they can
be fixed at almost no cost as compared to a later stage, let’s say during production, which can
be really expensive.

How to perform Unit testing of React Apps using JEST?


Jest is a JavaScript testing framework that allows developers to run tests on JavaScript and
TypeScript code and can be easily integrated with React JS.
Step 1: Create a new react app
For unit testing a react app, let’s create one using the command given below:
npx create-react-app react-testing-tutorial

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

Open the package.json, and you will find that when you use create-react-app for creating a
react project, it has default support for jest and react testing library. This means that we do
not have to install them manually.
Step 2: Create a component
Let’s create a component called Counter, which simply increases and decreases a numeric
value at the click of respective buttons.
import React, { useState } from "react";

const Counter = () => {

const [counter, setCounter] = useState(0);

const incrementCounter = () => {

setCounter((prevCounter) => prevCounter + 1);

};

const decrementCounter = () => {

setCounter((prevCounter) => prevCounter - 1);

};

return (

<>

<button data-testid="increment" onClick={incrementCounter}>

</button>

<p data-testid="counter">{counter}</p>

<button disabled data-testid="decrement" onClick={decrementCounter}>

</button>

</>

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

);

};

export default Counter;

Step 3: Write a unit test for the react component


Before writing an actual unit test, let’s understand the general structure of a test block:

 A test is usually written in a test block.


 Inside the test block, the first thing we do is to render the component that we want to test.
 Select the elements that we want to interact with
 Interact with those elements
 Assert that the results are as expected.
The unit test of react component can be written as seen in the code snippet below:
import { render, fireEvent, screen } from "@testing-library/react";

import Counter from "../components/Counter";

//test block

test("increments counter", () => {

// render the component on virtual dom

render(<Counter />);

//select the elements you want to interact with

const counter = screen.getByTestId("counter");

const incrementBtn = screen.getByTestId("increment");

//interact with those elements

fireEvent.click(incrementBtn);

//assert the expected result

expect(counter).toHaveTextContent("1");

});

K.SONI SHARMILA,CSE DEPT.,SVECW


REACT ADVANCED CONCEPTS

Note: In order to let jest know about this test file, it’s important to use the extension .test.js.
The above test can be described as:

 The test block can be written either using test() or it(). Either of the two methods takes two
parameters:
o The first parameter is to name the test. For example, increments counter.

o The second parameter is a callback function, which describes the actual test.
 Using the render() method from the react testing library in the above test to render the
Counter component in a virtual DOM.
 The screen property from the react testing library helps select the elements needed to test by
the test ids provided earlier.
 To interact with the button, using the fireEvent property from the react testing library in the
test.
 And finally, it is asserted that the counter element will contain a value ‘1’.
Step 4: Run the test
Run the test using the following command:
npm run test

Test Result

K.SONI SHARMILA,CSE DEPT.,SVECW


NODE.JS

UNIT-3

Node.js

3.1.NODE.JS INTRODUCTION:
Node.js is an open-source server side runtime environment built on Chrome's V8 JavaScript
engine. It provides an event driven, non-blocking (asynchronous) I/O and cross-platform
runtime environment for building highly scalable server-side application using JavaScript.

Node.js can be used to build different types of applications such as command line
application, web application, real-time chat application, REST API server etc. However, it
is mainly used to build network programs like web servers, similar to PHP, Java, or
ASP.NET.

Advantages of Node.js
1. Node.js is an open-source framework under MIT license. (MIT license is a free software
license originating at the Massachusetts Institute of Technology (MIT).)
2. Uses JavaScript to build entire server side application.
3. Lightweight framework that includes bare minimum modules. Other modules can be
included as per the need of an application.
4. Asynchronous by default. So it performs faster than other frameworks.
5. Cross-platform framework that runs on Windows, MAC or Linux

3.2.Node.js Module
Module in Node.js is a simple or complex functionality organized in single or multiple
JavaScript files which can be reused throughout the Node.js application.

Each module in Node.js has its own context, so it cannot interfere with other modules or
pollute global scope. Also, each module can be placed in a separate .js file under a separate
folder.

Node.js implements CommonJS modules standard. CommonJS is a group of volunteers who


define JavaScript standards for web server, desktop, and console application.

Node.js Module Types

Node.js includes three types of modules:

1. Core Modules
2. Local Modules
3. Third Party Modules

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

3.3.Node.js Core Modules


Node.js is a light weight framework. The core modules include bare minimum
functionalities of Node.js. These core modules are compiled into its binary distribution and
load automatically when Node.js process starts. However, you need to import the core
module first in order to use it in your application.

The following table lists some of the important core modules in Node.js.

Core Module Description

http http module includes classes, methods and events to create Node.js http server.

url url module includes methods for URL resolution and parsing.

querystring querystring module includes methods to deal with query string.

path path module includes methods to deal with file paths.

fs fs module includes classes, methods, and events to work with file I/O.

util util module includes utility functions useful for programmers.

Loading Core Modules

In order to use Node.js core or NPM modules, you first need to import it using require()
function as shown below.

var module = require('module_name');

As per above syntax, specify the module name in the require() function. The require()
function will return an object, function, property or any other JavaScript type, depending on
what the specified module returns.

The following example demonstrates how to use Node.js http module to create a web server.

Example: Load and Use Core http Module

var http = require('http');

var server = http.createServer(function(req, res){

//write code here

});

server.listen(5000);

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

In the above example, require() function returns an object because http module returns its
functionality as an object, you can then use its properties and methods using dot notation
e.g. http.createServer().

Node.js Local Module

Local modules are modules created locally in your Node.js application. These modules
include different functionalities of your application in separate files and folders. You can
also package it and distribute it via NPM, so that Node.js community can use it. For example,
if you need to connect to MongoDB and fetch data then you can create a module for it, which
can be reused in your application.

Writing Simple Module

Let's write simple logging module which logs the information, warning or error to the
console.

In Node.js, module should be placed in a separate JavaScript file. So, create a Log.js file
and write the following code in it.

Log.js

var log = {
info: function (info) {
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
};

module.exports = log

In the above example of logging module, we have created an object with three functions -
info(), warning() and error(). At the end, we have assigned this object to module.exports.
The module.exports in the above example exposes a log object as a module.

The module.exports is a special object which is included in every JS file in the Node.js
application by default. Use module.exports or exports to expose a function, object or
variable as a module in Node.js.

Now, let's see how to use the above logging module in our application.

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

Loading Local Module

To use local modules in your application, you need to load it using require() function in the
same way as core module. However, you need to specify the path of JavaScript file of the
module.

The following example demonstrates how to use the above logging module contained in
Log.js.

app.js

var myLogModule = require('./Log.js');

myLogModule.info('Node.js started');

In the above example, app.js is using log module. First, it loads the logging module using
require() function and specified path where logging module is stored. Logging module is
contained in Log.js file in the root folder. So, we have specified the path './Log.js' in the
require() function. The '.' denotes a root folder.

The require() function returns a log object because logging module exposes an object in
Log.js using module.exports. So now you can use logging module as an object and call any
of its function using dot notation e.g myLogModule.info() or myLogModule.warning() or
myLogModule.error()

Run the above example using command prompt (in Windows) as shown below.

C:\> node app.js

Info: Node.js started

Thus, you can create a local module using module.exports and use it in your application.

Export Module in Node.js

Here, you will learn how to expose different types as a module using module.exports.

The module.exports is a special object which is included in every JavaScript file in the
Node.js application by default. The module is a variable that represents the current module,
and exports is an object that will be exposed as a module. So, whatever you assign
to module.exports will be exposed as a module.

Let's see how to expose different types as a module using module.exports.

Export Literals

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

As mentioned above, exports is an object. So it exposes whatever you assigned to it as a


module. For example, if you assign a string literal then it will expose that string literal as a
module.

The following example exposes simple string message as a module in Message.js.

Message.js

module.exports = 'Hello world';

Now, import this message module and use it as shown below.

app.js

var msg = require('./Messages.js');

console.log(msg);

Run the above example and see the result, as shown below.

C:\> node app.js

Hello World

3.4.NPM - Node Package Manager


Node Package Manager (NPM) is a command line tool that installs, updates or uninstalls
Node.js packages in your application. It is also an online repository for open-source Node.js
packages. The node community around the world creates useful modules and publishes them
as packages in this repository.

NPM is included with Node.js installation. After you install Node.js, verify NPM installation
by writing the following command in terminal or command prompt.

C:\>npm -v

If you have an older version of NPM then you can update it to the latest version using the
following command.
C:/> npm install npm -g

To access NPM help, write npm help in the command prompt or terminal window.

C:\> npm help

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

NPM performs the operation in two modes: global and local. In the global mode, NPM
performs operations which affect all the Node.js applications on the computer whereas in
the local mode, NPM performs operations for the particular local directory which affects an
application in that directory only.

Install Package Locally

Use the following command to install any third party module in your local Node.js project
folder.

C:\>npm install <package name>

For example, the following command will install ExpressJS into MyNodeProj folder.

C:\MyNodeProj> npm install express

All the modules installed using NPM are installed under node_modules folder. The above
command will create ExpressJS folder under node_modules folder in the root folder of your
project and install Express.js there.

Add Dependency into package.json

Use --save at the end of the install command to add dependency entry into package.json of
your application.

For example, the following command will install ExpressJS in your application and also
adds dependency entry into the package.json.

C:\MyNodeProj> npm install express –save

Install Package Globally

NPM can also install packages globally so that all the node.js application on that computer
can import and use the installed packages. NPM installs global packages
into /<User>/local/lib/node_modules folder.

Apply -g in the install command to install package globally. For example, the following
command will install ExpressJS globally.

C:\MyNodeProj> npm install -g express

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

Update Package

To update the package installed locally in your Node.js project, navigate the command
prompt or terminal window path to the project folder and write the following update
command.

C:\MyNodeProj> npm update <package name>

The following command will update the existing ExpressJS module to the latest version.

C:\MyNodeProj> npm update express

Uninstall Packages

Use the following command to remove a local package from your project.

C:\>npm uninstall <package name>

The following command will uninstall ExpressJS from the application.

C:\MyNodeProj> npm uninstall express

3.5.Build a Secure Server with Node.js

Install Node.js and NPM


If you haven't yet done so, you'll need to install Node and npm on your machine.

1. Go to the Node.js website

2. Click on the recommended download button

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

NODE HOME PAGE


When the download is complete, install Node using the downloaded .exe file (it follows the
normal installation process).
Check if the installation was successful
1. Go to your terminal/command prompt (run as administrator if possible)

2. Type in each of the following commands and hit Enter

node -v
npm -v
Your output should be similar to the image below:

Terminal showing
the versions of node and npm
The version may be different but that's OK.

How to Create a Node Server without Express


Let's start by creating a project directory. Open a terminal and type the following to create a
directory and open it:

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

mkdir server-tut

cd server-tut

In the terminal, type npm init. Hit the Enter button for all prompts. When completed, you
should have a package.json file seated in your project directory.
The package.json file is just a file with all the details of your project. You don't have to open
it.
Create a file called index.js.
In the file, require the HTTP module like so:
const http = require('http');
Call the createServer() method on it and assign it to a constant like this:
const server = http.createServer();
Call the listen() method on the server constant like this:
server.listen();
Give it a port to listen to. Now this could be any free port, but we will be using
port 3000 which is the conventional port. So we have this:
const http = require('http');

const server = http.createServer();

server.listen(3000);
Basically, that is all you need do to create a server.

How to Test the Server


In your terminal (should be in the project directory), type node index.js and hit
the Enter button.
Open a new tab in postman or any web browser and in the address bar,
type http://localhost:3000/, and hit the Enter button. (I will be using postman because of its
extended functionality outside the box.)
You will notice that your browser or postman keeps loading indefinitely like so:

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

Yay! That is fine. Our Server is up and running.

We need to make the server talk to us.

How to Send Back a Response from the Server


Back in the code, add the following to const server = http.createServer();:
(request, response) => {
response.end('Hey! This is your server response!');
}
So we now have:

const http = require('http');

const server = http.createServer((request, response) => {


response.end('Hey! This is your server response!');
});

server.listen(3000);

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

In basic terms, the request object tells the server that we want something, the response object
tells us what the server has to say about our request, and the end() method terminates the
communication with the server response.
Hopefully, that makes sense!

Now, test the server again following the steps we outlined above and your server should be
talking to you. This is my output:

Feel free to change the string as you wish.

Use Control/Command + C to terminate the server and run node index to start the server
again.
How to Create a Node Server With Express
In this section, we want to make our lives easier by using Express and Nodemon (node-mon
or no-demon, pronounce it as you wish).
In the terminal, install the following:

npm install express --save


npm install nodemon --save-dev
Create a new file named app.js or whatever suits you

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

In the file,

1. Require express like so:


const express = require('express');
2. Assign the express method to a constant like this:

const app = express();


3. Export the app constant to make it available for use in other files within the directory like
so:

module.exports = app;
So we have:

const express = require('express');

const app = express();


module.exports = app;
In the index.js file, require the app we exported a while ago:
const app = require('./app');
Next, set the port using the app like so:

app.set('port', 3000);
And replace the code in the http.createServer() method with just app like this:
const server = http.createServer(app);
This directs all API management to the app.js file helping with separation of concerns.
So our index.js file now looks like this:
const http = require('http');
const app = require('./app');

app.set('port', 3000);
const server = http.createServer(app);

server.listen(3000);
Back in our app.js file, since we have directed all API management to it, let's create an
endpoint to speak to us like before.
So before the module.exports = app, add the following code:
app.use((request, response) => {
response.json({ message: 'Hey! This is your server response!' });
});
We now have:

const express = require('express');

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

const app = express();

app.use((request, response) => {


response.json({ message: 'Hey! This is your server response!' });
});

module.exports = app;
Ahaaa... It's time to test our app.

To test our app, we now type nodemon index in our terminal and hit the Enter button. This is
my terminal:

Do you notice that nodemon gives us details of execution in the terminal unlike Node? That's
the beauty of nodemon.

You can now go to postman or any browser and in the address bar,
type http://localhost:3000/ and hit Enter. See my output:

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

Now more reasons to use nodemon. Go to the app.js file and change the message string to
any string on your choice, save, and watch the terminal.

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

Wow... It automatically restarts the server. This was impossible with Node. We had to restart
the server ourselves.

3.6.Node.js Debugging:
Debugging is a concept to identify and remove errors from software applications. In this
article, we will learn about the technique to debug a Node.js application.
Why not to use console.log()?
Using console.log to debug the code generally dives into an infinite loop of “stopping the
app and adding a console.log, and start the app again” operations. Besides slowing down
the development of the app, it also makes the writing dirty and creates unnecessary code.
Finally, trying to log out variables alongside with the noise of other potential logging
operations, may make the process of debugging difficult when attempting to find the values
you are debugging.
How to debug?
Mostly we used console.log() but as mentioned above, it is not always a good practice. We
can use a V8 inspector for it.
Steps for debugging:
1. Write the following code in the terminal window as shown below:
node --inspect-brk-filename.js

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

2. Open your Chrome browser and write inspect as shown below:

3. Now click on Open Dedicated DevTools for Node.

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

4. Now, click on the Node.js icon. The terminal will show the following message:

Other tools to help launch a DevTools window:


june07.com/nim
github.com/jaridmargolin/inspect-process
github.com/darcyclarke/rawkit
Additional Debugging APIs:
1. Debugging an existing Node process:
2. process._debugProcess(pid);</pre
3. GDB-like CLI Debugger:
4. node inspect filename.js
5. Drive with DevTools Protocol via WS port:

const dp = require('chrome-remote-interface');

async function test() {


const client = await dp();
const {Profiler, Runtime} = client;

await Profiler.enable();
await Profiler.setSamplingInterval({interval: 500});

await Profiler.start();
await Runtime.evaluate({expression: 'startTest();'});
await sleep(800);

const data = await Profiler.stop();


require('fs').writeFileSync('data.cpuprofile',
JSON.stringify(data.profile));
};

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

test().then((result)=>{
console.log(result);
})
.catch((error)=>{
console.log(error);
});

6. DevTools Protocol via require('inspector'):

const inspector = require('inspector');

const fs = require('fs');

const session = new inspector.Session();

session.connect();

session.post('Profiler.enable');

session.post('Profiler.start');

setTimeout( function() {

session.post('Profiler.stop',

function(err, data) {

fs.writeFileSync('data.cpuprofile',

JSON.stringify(data.profile));

});

}, 8000);

Another awesome thing in using Chrome as a debugging tool is that you can debug both
your front-end and back-end JavaScript code with the same interface.
3.7.What is inspector in Node.js?
Inspector in node.js is a debugging interface for node.js application that is contained in the
app.js file and used blink developer tools. It works almost similar to chrome developer
tools. It can support almost all the feature that a debugger generally have such as navigating

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

to source files, setting breakpoints, CPU and heap profiling, network client requests
inspection, console output inspections, and many other features.
How to install?
It can be installed by running the following command in the command line after installing
npm (node package manager).
$ npm install -g node-inspector
Here in the command, -g flag corresponds to global installation of the inspector. After
installing if you run command node-inspector, we get an output like this:

After successful installation

In the above figure, it displays an URL for debugging purpose. So, when we point our
browser to http://127.0.0.1:8080/?port=5858, we get a GUI for debugging. Sometimes,
port 8080 may not be available on the computer then we will get an error. We can change
the port (in this case port 5555) on which node-inspector is running by using the following
command:
$ node-inspector --web-port=5555
How to start using it?
It can be started using following command in command line:
$ node-debug app.js
where app.js is the name of the main JavaScript application file. Available configuration
options can be seen here.

While debugging app.js file

The node-debug command will load Node Inspector in the default browser.
Note: Node Inspector works in Chrome and Opera only.
Advanced Use: While running node-debug is an easy way to start your debugging session,
sometimes we need to tweak the default setup. Then we need to follow three steps given
below
1. Start the node-inspector server: This can be done by running command:
$ node-inspector
The server can be left running in the background, it is possible to debug multiple
processes using the same server instance.
2. Enable debug mode in the node process: You can either start Node with a debug flag
like:
$ node --debug your/node/program.js
or, to pause your script on the first line:
$ node --debug-brk your/short/node/script.js

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

Or one can enable debugging on a node that is already running by sending it a signal:
1. Get the PID of the node process using your favorite method. pgrep or ps -ef are
good.
$ pgrep -l node
2345 node your/node/server.js
2. Send it the USR1 signal
$ kill -s USR1 2345
3. Load the debugger UI: Open http://127.0.0.1:8080/?port=5858 or the produced URL
in the Chrome browser.
Node.js is a widely used javascript library based on Chrome’s V8 JavaScript engine for
developing server-side applications in web development.
3.8.TESTING IN NODE.JS
Unit Testing is a software testing method where individual units/components are tested in
isolation. A unit can be described as the smallest testable part of code in an application.
Unit testing is generally carried out by developers during the development phase of an
application.
In Node.js there are many frameworks available for running unit tests. Some of them are:
 Mocha
 Jest
 Jasmine
 AVA
Unit testing for a node application using these frameworks:
1. Mocha: Mocha is an old and widely used testing framework for node applications. It
supports asynchronous operations like callbacks, promises, and async/await. It is a
highly extensible and customizable framework that supports different assertions and
mocking libraries.
To install it, open command prompt and type the following command:
# Installs globally
npm install mocha -g
# installs in the current directory
npm install mocha --save-dev
How to use Mocha?
In order to use this framework in your application:
1. Open the root folder of your project and create a new folder called test in it.
2. Inside the test folder, create a new file called test.js which will contain all the code
related to testing.
3. open package.json and add the following line in the scripts block.
4. "scripts": {
5. "test": "mocha --recursive --exit"
}

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

Example:

// Requiring module
const assert = require('assert');

// We can group similar tests inside a describe block


describe("Simple Calculations", () => {
before(() => {
console.log( "This part executes once before all tests" );
});

after(() => {
console.log( "This part executes once after all tests" );
});

// We can add nested blocks for different tests


describe( "Test1", () => {
beforeEach(() => {
console.log( "executes before every test" );
});

it("Is returning 5 when adding 2 + 3", () => {


assert.equal(2 + 3, 5);
});

it("Is returning 6 when multiplying 2 * 3", () => {


assert.equal(2*3, 6);
});
});

describe("Test2", () => {
beforeEach(() => {
console.log( "executes before every test" );
});

it("Is returning 4 when adding 2 + 3", () => {


assert.equal(2 + 3, 4);
});

it("Is returning 8 when multiplying 2 * 4", () => {


assert.equal(2*4, 8);
});
});
});

Copy the above code and paste it in the test.js file that we have created before. To run
these tests, open the command prompt in the root directory of the project and type the
following command:
npm run test
Output:

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

What is Chai?
Chai is an assertion library that is often used alongside Mocha. It can be used as a TTD
(Test Driven Development) / BDD (Behavior Driven Development) assertion library for
Node.js that can be paired up with any testing framework based on JavaScript. Similar
to assert.equal() statement in the above code, we can use Chai to write tests like English
sentences.
To install it, open the command prompt in the root directory of the project and type the
following command:
npm install chai

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

Example:

const expect = require('chai').expect;

describe("Testing with chai", () => {


it("Is returning 4 when adding 2 + 2", () => {
expect(2 + 2).to.equal(4);
});

it("Is returning boolean value as true", () => {


expect(5 == 5).to.be.true;
});

it("Are both the sentences matching", () => {


expect("This is working").to.equal('This is working');
});
});

Output:

2. Jest: Jest is also a popular testing framework that is known for its simplicity. It is
developed and maintained regularly by Facebook. One of the key features of jest is it is
well documented, and it supports parallel test running i.e. each test will run in their own
processes to maximize performance. It also includes several features like test watching,
coverage, and snapshots.
You can install it using the following command:
npm install --save-dev jest
Note: By default, Jest expects to find all the test files in a folder called “__tests__” in
your root folder.
Example:

describe("Testing with Jest", () => {


test("Addition", () => {
const sum = 2 + 3;
const expectedResult = 5;
expect(sum).toEqual(expectedResult);
});

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

// Jest also allows a test to run multiple


// times using different values
test.each([[1, 1, 2], [-1, 1, 0], [3, 2, 6]])(
'Does %i + %i equals %i', (a, b, expectedResult) => {
expect(a + b).toBe(expectedResult);
});
});

Output:

3. Jasmine: Jasmine is also a powerful testing framework and has been around since
2010. It is a Behaviour Driven Development(BDD) framework for testing JavaScript
code. It is known for its compatibility and flexibility with other testing frameworks like
Sinon and Chai. Here test files must have a specific suffix (*spec.js).
You can install it using the following command:

K.SONI SHARMILA,CSE DEPT,SVECW


NODE.JS

npm install jasmine-node


Example:

describe("Test", function() {
it("Addition", function() {
var sum = 2 + 3;
expect(sum).toEqual(5);
});
});

4. AVA: AVA is a relatively new minimalistic framework that allows you to run your
JavaScript tests concurrently. Like the Jest framework, it also supports snapshots and
parallel processing which makes it relatively fast compared to other frameworks. The
key features include having no implicit globals and built-in support for asynchronous
functions.
You can install it using the following command:
npm init ava
Example:

import test from 'ava';

test('Addition', t => {
t.is(2 + 3, 5);
});

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

Unit-4

Mongo DB
4.1.What is Mongo DB?

As a definition, Mongo DB is an open-source database that uses a document-oriented data


model and a non-structured query language. It is one of the most powerful NoSQL systems and
databases around, today.

Mongo DB Atlas is a cloud database solution for contemporary applications that is available
globally. This best-in-class automation and established practices offer to deploy fully managed
Mongo DB across AWS, Google Cloud, and Azure.

It also ensures availability, scalability, and compliance with the most stringent data security
and privacy requirements. Mongo DB Cloud is a unified data platform that includes a global
cloud database, search, data lake, mobile, and application services

4.2.History of Mongo DB

Dwight Merriman, Eliot Horowitz, and Kevin Ryan created Mongo DB in 2007. To provide a
solution for the problems of scalability and agility that they were facing at DoubleClick, they
decided to develop a database. That’s when Mongo DB came into existence.

 MongoDB was first developed by 10gen Software in 2007 as part of a proposed


platform as a service solution.
 The firm switched to an open-source development approach in 2009, with commercial
support and additional services available.
 MongoDB Inc. replaced 10gen as the company’s name in 2013.
 It became a publicly traded business on October 20, 2017, when it was listed on
NASDAQ as MDB with an IPO price of $24 per share.

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

 It announced a partnership with Alibaba Cloud on October 30, 2019, to provide a


MongoDB-as-a-Service solution to its clients. Customers can access BABA’s managed
services from any of the company’s worldwide data centres.

4.3.Installing MongoDB on Windows


What’s Mongo DB?

Mongo DB is a document database which belongs to a family of databases called NoSQL -


not only SQL. In Mongo DB, records are documents which behave a lot like JSON objects in
JavaScript. Values in documents can be looked up by their field’s key. Documents can have
some fields/keys and not others, which makes Mongo extremely flexible.

This is different than SQL databases like MySQL and PostgreSQL, where fields correspond
to columns in a table and individual records correspond to rows.

Prerequisites

You should have a general familiarity with the Windows command prompt.

Installing and Running Mongo DB on a Windows Machine

 Download the MongoDB installer file from the downloads section of the MongoDB
website.

 Find the dowloaded .msi file in the Windows Explorer. Double click the file and follow
the prompts to install Mongo. Note: unless you specify a custom directory Mongo is most
likely installed in the C:\mongodb directory**. However, based on settings on your
machine Mongo may be installed other places. For example, C:\Program
Files\MongoDB\Server\3.2 . Additionally, you may find MongoDB in the add/remove
programs menu.

 Create the directory where MongoDB will store it’s files. From the command prompt
run md \data\db . This is the default location. However, other locations can be specified
using the --dbpath parameter. See the Mongo docs for more information.

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

 Start the mongodb daemon by running C:\mongodb\bin\mongod.exe in the Command


Prompt. Or by running, C:\path\to\mongodb\bin\mongod.exe

 Connect to MongoDB using the Mongo shell While the MongoDB daemon is running,
from a different Command prompt window run C:\mongodb\bin\mongo.exe

4.3.1.How to setup a local MongoDB Connection


Once you have completed the installation process, try typing mongo --version into your
command line. You should get a response similar to the following:

mongo --version

4.4.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:

1. $ mongo

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

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.

Let us take a simple mathematical program:

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

You can also use the JavaScript libraries

1. > "Hello, World!".replace("World", "MongoDB");

Hello, MongoDB!
Note: You can create multiple commands.

When you press "Enter", the shell detect whether the JavaScript statement is complete or not.

If the statement is not completed, the shell allows you to continue writing it on the next line. If
you press "Enter" three times in a row, it will cancel the half-formed command and get you
back to the > - prompt.

4.5. Introduction to MongoDB Collection

We have a table in the relational database management system. In MongoDB, we have a

collection to store N number of records that are documented. Collection stores N number of

documents. MongoDB accepts unstructured data. Document stores data which is not in

structure format because MongoDB is a schema-less database. We don’t need to define

column and datatype while creating a collection. Collection name starts with name or

namespace, and it can have any numbers. The collection name should not exceed 128

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

characters. By using (.), the collection gets organized into groups. We can create any number

of collections in the database. We should first create a database to store the collection value.

How does Collection Methods work in MongoDB?


1. We first need a MongoDB database to create a collection.
USE<"database name">
2. Mention Collection name and insert a record into it.
collection_name.create(<document>)
3. Collection Gets Created.
4. We can view any number of collections with command.
show collections
Syntax
1. To create a collection
db.collection_name(field:value)
2. To delete collection
collection_name.drop()

Examples to Implement MongoDB Collection


Below are the examples of implementing MongoDB Collection:

A) Create a Collection
1. We have created a database named hospital.
Code:
use hospital
Output:

2. We have created a collection named the patient.


Code:
db.patient.insert({})
Output:

 If we don’t enter any value inside (), then an error will appear. Error: no object passed

to insert!

3. We have inserted a record for the patient with field: value pair.
Code:
db.patient.insert({name:'akash',age:23,reason:'fever'})

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

Be careful while creating record because if we don’t use ( ‘ ‘) for the string, then an error will appear.

“nInserted”:1 means record inserted successfully.


4. To show the list of collections.
Code:
show collections
Output:

5. We have inserted multiple records into the patient collection.


Code:
db.patient.insert({name:'megha',age:24,reason:'fever'},{name:'rohit',age:25,reason:'cuff'})
Output:

6. We have inserted the record into the patient history.


Code:
db.patienthistory.insert({name:'rupali',age:34,experience:12})
Output:

B) Delete Collection (drop the collection)


We can delete the collection from the database. Select the database from which you want to delete
the collection.
USE <database name>
Verify if the collection is present or not with <show collections>.
Apply drop command with a collection.
1. We have used the hospital database.
Code:
use hospital
Output:

Code:
db.patienthistory.drop()
Output:

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

We get the true message which means collection deleted successfully.


If the false message is displayed, then the collection is not deleted yet.
2. We have checked the collection list. We can observe that patient history is not present.
Code:
show collections
Output:

3. If we try to delete the non-existing collection, then the false message is displayed.
Code:
db.library.drop()
Output:

1. Find ()
1. This command will display data from collection means documents/records inserted into the
collection.
Syntax:
db.collection_name.find()
Code:
db.patient.find()
_id – it is defined for each document by default if we do not mention it while creating a document.
We have inserted name, age and reason for each patient.
We can observe that no data is present in the first record because we have created a document
without field: value pair.
Output:

2. We have created a document with a collection with no record.


Syntax:
collection_name.insert({})
Code:
db.injection.insert({})
Output:

2. Filtering collection
If we have a huge dataset and want to find a particular value or fetch certain records, then find () will
help us.
Syntax:
db.collection_name.find({field:value})
Code:

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

db.patient.find({name:"akash"})
Output: It has fetched all the details of Akash from the patient collection.

4.6.CRUD OPERATIONS
MongoDB is a document database. A record in MongoDB is a document, which is a data
structure composed of key value pairs similar to the structure of JSON objects.
Records in a MongoDB database are called documents, and the field values may include
numbers, strings, booleans, arrays, or even nested documents.

title: "Post Title 1",

body: "Body of post.",

category: "News",

likes: 1,

tags: ["news", "events"],

date: Date()

Create a Database
use blog
switched to db blog
Create Collection using mongosh

There are 2 ways to create a collection.

Method 1

You can create a collection using the createCollection() database method.

Example
db.createCollection("posts")
Method 2

You can also create a collection during the insert process.

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

Example

We are here assuming object is a valid JavaScript object containing post data:

db.posts.insertOne(object)
MongoDB mongosh Insert
Insert Documents

There are 2 methods to insert documents into a MongoDB database.

insertOne()

To insert a single document, use the insertOne() method.

This method inserts a single object into the database.

db.posts.insertOne({

title: "Post Title 1",

body: "Body of post.",

category: "News",

likes: 1,

tags: ["news", "events"],

date: Date()

})

insertMany()

To insert multiple documents at once, use the insertMany() method.

This method inserts an array of objects into the database.

db.posts.insertMany([

title: "Post Title 2",

body: "Body of post.",

category: "Event",

likes: 2,

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

tags: ["news", "events"],

date: Date()

},

title: "Post Title 3",

body: "Body of post.",

category: "Technology",

likes: 3,

tags: ["news", "events"],

date: Date()

},

title: "Post Title 4",

body: "Body of post.",

category: "Event",

likes: 4,

tags: ["news", "events"],

date: Date()

])

MongoDB mongosh Find


Find Data

There are 2 methods to find and select data from a MongoDB


collection, find() and findOne().

find()

To select data from a collection in MongoDB, we can use the find() method.

This method accepts a query object. If left empty, all documents will be returned.

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

db.posts.find()

findOne()

To select only one document, we can use the findOne() method.

This method accepts a query object. If left empty, it will return the first document it finds.

db.posts.findOne()

db.posts.find( {category: "News"} )

Update Document

To update an existing document we can use the updateOne() or updateMany() methods.

The first parameter is a query object to define which document or documents should be
updated.

The second parameter is an object defining the updated data.

updateOne()

The updateOne() method will update the first document that is found matching the provided
query.

Let's see what the "like" count for the post with the title of "Post Title 1":

db.posts.updateOne( { title: "Post Title 1" }, { $set: { likes: 2 } } )

Delete Documents

We can delete documents by using the methods deleteOne() or deleteMany().

These methods accept a query object. The matching documents will be deleted.

deleteOne()

The deleteOne() method will delete the first document that matches the query provided.

db.posts.deleteOne({ title: "Post Title 5" })

deleteMany()

The deleteMany() method will delete all documents that match the query provided.

db.posts.deleteMany({ category: "Technology" })

4.7.Top MongoDB Alternatives

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

 Amazon Web Services (AWS)


 Oracle.
 Microsoft.
 MariaDB.
 Google.
 Couchbase.
 IBM.
 Cloudera.

4.8.INTERACTING WITH MONGODB USING MONGOOSE:

You can connect to MongoDB with the mongoose.connect() method.

mongoose.connect('mongodb://127.0.0.1:27017/myapp');

This is the minimum needed to connect the myapp database running locally on the default
port (27017). If connecting fails on your machine, try using 127.0.0.1 instead of localhost.

You can also specify several more parameters in the uri:

mongoose.connect('mongodb://username:password@host:port/database?options...');

See the mongodb connection string spec for more details.

 Buffering
 Error Handling
 Options
 Connection String Options
 Connection Events
 A note about keepAlive
 Server Selection
 Replica Set Connections
 Replica Set Host Names
 Multi-mongos support
 Multiple connections
 Connection Pools

4.9.cloud hosting in mongodb


MongoDB Atlas is an example of a DBaaS. This is the cloud-hosted solution for
MongoDB's Document Databases. It supports all three major cloud providers (AWS, Azure,

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

and GCP) including a multi-cloud setup should you wish to target specific regions or data
centers across providers.

What is MongoDB Atlas?

Database-as-a-Service (DBaaS) is a service that allows you to set up, deploy, and scale a
database without worrying about on-premise physical hardware, software updates, and the
details of configuring for performance. With DBaaS, a cloud provider does all that for you—
and gets you up and running right away.

MongoDB Atlas is a fully-managed cloud database that handles all the complexity of
deploying, managing, and healing your deployments on the cloud service provider of your
choice (AWS , Azure, and GCP). MongoDB Atlas is the best way to deploy, run, and scale
MongoDB in the cloud. With Atlas, you’ll have a MongoDB database running with just a few
clicks, and in just a few minutes.

To begin using MongoDB Atlas, you’ll need to do the following:

1. Create a MongoDB Cloud account.


2. Create a MongoDB Atlas cluster.
3. Configure network access and create a cluster user.
4. Connect to the cluster.

MongoDB Atlas has a free tier, so you won’t need any payment or credit card information.

Creating a MongoDB Atlas Account

Registration

In order to create an Atlas account, navigate


to https://www.mongodb.com/cloud/atlas/register.

You can sign up using your Google account. This would be the preferred method; however,
you can also register using your email address.

Organizations and Projects

At the end of the sign-up process, you will be prompted to create an organization and a
project.

Organizations allow you to group and define users and teams, and grant them access to the
different projects.

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

Projects allow you to define and organize resources such as database clusters, triggers, and
data lakes. A common way to use projects is to define each environment as a project. For
example, you can have a separate project for development, testing, and production.

You can skip this step and go directly to the management console for MongoDB Atlas. But
you will need an organization and a project in order to create a database cluster, so it makes
sense to do this step now. If you decide to skip it, you’ll be able to create an organization and
a project later.

Setting Up a Cluster in MongoDB Atlas

Once you have an Atlas account and have created an organization and a project, you’ll be
able to create a database cluster.

Make sure you have the desired organization and project selected in the top navigation
dropdowns. Then, select “Clusters” from the left navigation menu and click on the Build a
Cluster button.

You’ll be presented with a choice of Shared Cluster, Dedicated Cluster, and Multi-Cloud &
Multi-Region Cluster.

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

Shared Cluster is the least expensive (or free, depending on the usage) but it utilizes shared
hardware resources and network.

Dedicated Cluster provides you with a dedicated set of hardware and network isolation as
well as the option to scale automatically within a single region.

The Multi-Cloud & Multi-Region Cluster builds on top of what the dedicated cluster
provides. It offers the best availability since it can replicate data across multiple geographic
regions. It also allows the creation of multi-cloud clusters using any combination of cloud
providers: AWS, Azure, and GCP.

If you’d like to explore a little with the free tier, select the Shared Cluster.

Once you have selected the type of cluster, you’ll be able to choose from the top three cloud
providers (Amazon Web Services, Microsoft Azure, and Google Cloud Platform) and select a
region for hosting the cluster.

You’ll also be able to select the cluster tier and additional settings, such as turn on backup
and cluster name. Some options, such as the MongoDB version cloud backups, are only
available with the paid cluster tiers.

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

Once you are satisfied with your selection, click the Create Cluster button. It may take a
couple of minutes for Atlas to launch your cluster in the selected cloud hosting provider.

When the cluster is ready, you will see the cluster name with a green circle next to it,
indicating a successful setup. You will also see several metrics next to it indicating
connections, operations, and the size of your cluster.

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

Next, let’s connect to the cluster.

Accessing a MongoDB Atlas Cluster

In order to access your MongoDB Atlas cluster, you’ll need to enable network access for
your network or IP address and create a database user for connecting to the cluster. After that,
you can generate a connection string for your application or script.

Allowing Access to Your IP Address

For security reasons, new database clusters do not have network access enabled by default.
You need to enable network access explicitly by whitelisting the addresses that will connect
to the cluster.

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

Each entry can be an IP address, a subnet, or you can enable access from any location. In
general, you would grant access only to a list of subnets or IP addresses rather than grant
access to any location. This limits the connections your cluster accepts, making it more
secure.

To enable network access to your cluster, click on the Connect button from the clusters view
in the Atlas management console. This will open up the connection settings wizard.

In order to allow access from your current IP address, click on the Add your current IP
address button. If you need to access it from a different IP address or subnet, click on the Add
a different IP address button and enter the IP or a subnet using the CIDR notation, such as
172.10.1.0/24.

Creating a Cluster User

In order to connect to the database from a script or an application, you must first create a
MongoDB database user. The database user allows you to connect and use the databases.
Please note this is separate from the user that logs in and manages the clusters and resources
in Atlas.

Database users are created per project and have access to all the clusters in the project. You
can also assign different roles and privileges to the database users. Note that the first user you
create will automatically be granted administrative privileges.

Right below the network access settings, you can create a database user. First enter the
username and password and then click on the Create database user button.

If you later need to add more users to the project, you can do it from the Security tab.

Generating a Database Connection String

Depending on your application, you may need to install a driver (library) corresponding to
your platform in order to connect to a cluster in Atlas. You can see the full list of supported
drivers here. If you’re using Compass (the MongoDB UI application) or the mongo
shell application, the drivers are already built in.

Regardless of your application, you’ll need to generate a database connection string for your
cluster. If you are just creating your cluster, the last step in the process will allow you to
create a connection string. Once you have enabled network access and created a database
user, you can click on the Choose connection method button, which will allow you to

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

generate a connection string for your application. You can also create the connection string
by clicking on the Connect button on your cluster from the Clusters tab in Atlas.

Click on the Connect your application button and then select the driver, such as Node.js,
Python, or another language. Then, select the version to generate the connection string for
your application. You can even check the "Include full driver code example" option in order
to generate the code to test the connectivity.

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

Note that the connection string generated does not include the actual cluster user login. You
will need to replace the <username> and <password> with your actual username and
password. You will also need to replace MyFirstDatabase with an actual database name in
your cluster.

Sample Data

If you are just starting with MongoDB, you may want to load a sample data set.

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

From the cluster view in the Atlas management console, click on the ellipsis button [...] and
select “Load Sample Data” from the menu. Then confirm your selection.

This will load a few sample collections that you can use to run test queries and learn more
about MongoDB. You can view the sample collections loaded by clicking on the Collections
button on your cluster from the Clusters tab in Atlas.

Conclusion

K.SONI SHARMILA,CSE DEPT,SVECW


MONGODB

MongoDB Atlas is a great option for those who don’t have the time or resources to manage
all the infrastructure needed for a MongoDB cluster. You can have a cluster up and running
in minutes, allowing you to focus on your application instead of managing a database. And
with the free tier, it’s easy to start exploring.

Be sure to also check out the Atlas documentation and MongoDB University courses for
developers. They’re free and will provide you with more in-depth information about how to
use MongoDB with Java, Javascript, Python or C#/.Net.

K.SONI SHARMILA,CSE DEPT,SVECW


EXPRESS.JS

Unit-5
Express.js
5.1.Express introduction
Express.js is a small framework that works on top of Node.js web server functionality to simplify
its APIs and add helpful new features. It makes it easier to organize your application’s
functionality with middleware and routing. It adds helpful utilities to Node.js HTTP objects and
facilitates the rendering of dynamic HTTP objects.

Why Express ?
 Develops Node.js web applications quickly and easily.
 It’s simple to set up and personalise.
 Allows you to define application routes using HTTP methods and URLs.
 Includes a number of middleware modules that can be used to execute additional requests
and responses activities.
 Simple to interface with a variety of template engines, including Jade, Vash, and EJS.
 Allows you to specify a middleware for handling errors.
5.2.Building blocks of express.js
7 building blocks of express.js
 Server
 App
 Route
 Router
 Request
 Response
 Middeleware

5.3.What Is Middleware?
 A request handler with access to the application's request-response cycle is known as
middleware.

 It's a function that holds the request object, the response object, and the middleware
function.

 Middleware can also send the response to the server before the request.

 The next middleware function is commonly represented as a variable named next.

 Simply middleware is a function that can only be applied using routes.

 We can access and modify request and response data using middleware.

K.SONI SHARMILA,CSE DEPT,SVECW


EXPRESS.JS

Functions of Middleware

 Executes any code

 We can make changes to the request-response objects

 Middleware can also End the request-response cycle

 Middleware can call the next middleware function in a stack

We use these functions to modify our middleware to perform many tasks. If we want to block
our site for some country or if we're going to check the authentication of a user etc., we use
middleware for that.

K.SONI SHARMILA,CSE DEPT,SVECW


EXPRESS.JS

Creating Middleware
Now we will create an Express middleware for that we will create a simple Express API. We
can create middleware in a router file, but the easiest method is to create a separate middleware
file and then execute it; creating and using middleware is very simple.

So to create middleware, we need to install all the packages to run express middleware.

Fig - app.js

 Now open your terminal and run this file we will see our server is running.
 After this, go to the local server and type localhost:4000
 Now we will call our next parameter,
 In express framework, next is a function

K.SONI SHARMILA,CSE DEPT,SVECW


EXPRESS.JS

Fig - middleware

K.SONI SHARMILA,CSE DEPT,SVECW


EXPRESS.JS

5.4.Steps to create an Express.js Application


Express is the most popular minimalistic framework. It is built upon the built-in module
HTTP of NodeJS to facilitate the simple and easy interaction between frontend and backend
logic through API, and also it enables us to organize our business logic in so much pretty
manner. It is much flexible and we can use it for both the web and android. Also, it provides
a very simple error handling procedure.
Step by step Implementation:
Step 1: Write this command in your terminal, to create a nodejs application, because our
express server will work inside the node application.
Syntax:
npm init
This will ask you for few configurations about your project you can fill them accordingly,
also you can change it later from the package.json file.
Note: Use `npm init -y` for default initialization

Step 2: Install necessary dependencies for our application.


npm install express
Something like this will be shown on successful installation,

K.SONI SHARMILA,CSE DEPT,SVECW


EXPRESS.JS

Step 3: The project structure will look like following.

Create a file app.js, we will write the whole express code in that file. This will be our folder
structure. Now Inside app.js, Import express with require keyword and create an app by
calling the express() function provided by the express framework. Set the port for our local
application, 3000 is the default but you can choose any according to the availability of ports.
Call the listen() function, It requires path and callback as an argument. It starts listening to
the connection on the specified path, the default host is localhost, and our default path for the
local machine is the localhost:3000, here 3000 is the port which we have set earlier. The
callback function gets executed either on the successful start of the server or due to an error.
App.js
const express = require('express');
const app = express();
const PORT = 3000;
app.listen(PORT, (error) =>{
if(!error)
console.log("Server is Successfully Running,
and App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);

Step to run the application: Now as we have created a server we can successfully start
running it to see it’s working, write this command in your terminal to start the express
server.
node app.js
Output: You will see something like this on the terminal.

K.SONI SHARMILA,CSE DEPT,SVECW


EXPRESS.JS

Now with all of this, we have created and run the server successfully, if your server is not
starting then there may be some error, try to analyze and read that error and resolve it
accordingly.
Finally, after a successful run if you try to open the URL (localhost:3000) on the browser it
will show you cannot GET / because we have not configured any route on this application
yet.
Step 4: Now we will set all the routes for our application.
Routes are the endpoints of the server, which are configured on our backend server and
whenever someone tries to access those endpoints they respond accordingly to their
definition at the backend. If you’re a beginner you can consider route as a function that get s
called when someone requests the special path associated with that function and return the
expected value as a response. We can create routes for HTTP methods like get, post, put,
and so on.
Syntax: The basic syntax of these types of routes looks like this, the given function will
execute when the path and the request method resemble.
app.anyMethod(path, function)
Example 1: Setting up a basic get request route on the root URL (‘/’ path) of the server.
1. With app.get() we are configuring our first route, it requires two arguments first one is
the path and, the second one is a function that will be executed when anyone requests
this path with GET method. The express provides the request and response object as a
parameter to all such types of functions.
2. The req is a giant object which will be received from the user and res is an object
which will be sent to the user after the function finishes execution.
3. Later we are calling status() method it takes an HTTP status code as an argument and
when the response is returned, the status will be sent along.
4. Finally, we are returning the response to the user. The send() method takes a string,
object, array, or buffer as an argument and is used to send the data object back to the
client as an HTTP response, also there are lots of types of response in express like
res.json() which is used to send JSON object, res.sendFile() which is used to send a file,
etc.
Express.js POST Request

GET and POST both are two common HTTP requests used for building REST API's. POST
requests are used to send large amount of data.

Express.js facilitates you to handle GET and POST requests using the instance of express.

K.SONI SHARMILA,CSE DEPT,SVECW


EXPRESS.JS

Express.js POST Method

Post method facilitates you to send large amount of data because data is send in the body. Post
method is secure because data is not visible in URL bar but it is not used as popularly as GET
method. On the other hand GET method is more efficient and used more than POST.

Index.html

1. <html>
2. <body>
3. <form action="http://127.0.0.1:8000/process_post" method="POST">
4. First Name: <input type="text" name="first_name"> <br>
5. Last Name: <input type="text" name="last_name">
6. <input type="submit" value="Submit">
7. </form>
8. </body>
9. </html>
Postex.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.post('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port

K.SONI SHARMILA,CSE DEPT,SVECW


EXPRESS.JS

console.log("Example app listening at http://%s:%s", host, port)


})

Open the page index.html and fill the entries:

Now, you get the data in JSON format.

K.SONI SHARMILA,CSE DEPT,SVECW


EXPRESS.JS

5.5.express-jade
Jade is a template engine for Node.js. Jade syntax is easy to learn. It uses whitespace and
indentation as a part of the syntax.

Install jade into your project using NPM as below.

npm install jade

Jade template must be written inside .jade file. And all .jade files must be put
inside views folder in the root folder of Node.js application.

Note:

By default Express.js searches all the views in the views folder under the root
folder, which can be set to another folder using views property in express e.g.
app.set('views','MyViews').

The following is a simple jade template.

Sample.jade

doctype html
html
head
title Jade Page
body
h1 This page is produced by Jade engine
p some paragraph here..

The above example will produce following html.

<!DOCTYPE html>
<html>
<head>
<title>Jade Page</title>
</head>
<body>
<h1>This page is produced by Jade engine</h1>
<p>some paragraph here..</p>
</body>
</html>

K.SONI SHARMILA,CSE DEPT,SVECW


EXPRESS.JS

Server.js
var express = require('express');
var app = express();

//set view engine


app.set("view engine","jade")

app.get('/', function (req, res) {

res.render('sample');

});

var server = app.listen(5000, function () {


console.log('Node server is running..');
});
As you can see in the above example, first we import express module and then set the view
engine using app.set() method. The set() method sets the "view engine", which is one of
the application setting property in Express.js. In the HTTP Get request for home page, it
renders sample.jade from the views folder using res.render() method.

5.6.Clean Architecture in ExpressJS Applications (NodeJS)


Clean Architecture is a set of standards that aims to develop layered architectures that make it
easier to write quality code that will perform better, is easy to maintain, and has fewer
dependencies as the project grows. This architecture can be applied no matter what language
you code in.

K.SONI SHARMILA,CSE DEPT,SVECW


EXPRESS.JS

The Dependency Rule

Four layers of Clean Architecture


There are four concentric circles in Clean Architecture that each represents different areas of
Software, which are as below:
 Entities
 Use Cases
 Interface Adapters
 Frameworks and Drivers
The development team of Merlino also implemented another layer called Routes, and that's
totally okay. If you find that you may need more than four, just go on. However,
the Dependency Rule must always apply.
So, the four layers become five layers in our case study, which are as below:
 Entities (Mongoose models and their abstraction)
 Use Cases
 Interface Adapters (Controllers)
 Routes
 Frameworks and Drivers
1. Entities
At the center of the onion are the Entities of the software, which constitute the business logic
of software. An entity can be an object with methods, or it can be a set of data structures and
functions, they don't know anything about the outer layers and don't have any dependency.
In simple words, Entities are the primary concepts of your business.
2. Use Cases
The Use Cases layer, which lies outside the Entities layer, contains login and rules related to
the behavior and design of the system.
In simple words, Use Cases are interactions between Entities. For example, suppose we are
in our Social Media application example. In that case, we can have a Use Case like user
posts, or in the OneFood application, a customer places an order.

K.SONI SHARMILA,CSE DEPT,SVECW


EXPRESS.JS

Changes to this layer should not affect the entities. Changes to externalities such as the
database, user interface, or frameworks are unlikely to affect this layer.
3. Interface Adapters
The Interface Adapters or the Adapter layer holds the controllers, APIs, and gateways. The
Interface Adapters govern the flow of communication between external components and the
system's back-end.
In simple words, Interface Adapters are isolating our various Use Cases from the tools
that we use.
4. Routes
The /routes folder is where you can organize all of your different REST endpoints
declarations. The file below exposes all available endpoints related to the Orders Entity:

5. Frameworks and Drivers


The Frameworks and Drivers, also known as the Infrastructure Layer, is the outermost layer
that provides all necessary details about frameworks, drivers, and tools such as Databases that
we use to build our application. All the details of the system go in this layer.

K.SONI SHARMILA,CSE DEPT,SVECW


EXPRESSJS – ROUTING ExpressJS

Web frameworks provide resources such as HTML pages, scripts, images, etc. at different
routes.

The following function is used to define routes in an Express application:

app.method(path, handler)
This METHOD can be applied to any one of the HTTP verbs – get, set, put, delete. An alternate
method also exists, which executes independent of the request type.

Path is the route at which the request will run.

Handler is a callback function that executes when a matching request type is found on the
relevant route. For example,

var express = require('express');


var app = express();

app.get('/hello', function(req, res){


res.send("Hello World!");
});

app.listen(3000);

If we run our application and go to localhost:3000/hello, the server receives a get request
at route "/hello", our Express app executes the callback function attached to this route and
sends "Hello World!" as the response.

11
ExpressJS

We can also have multiple different methods at the same route. For example,

var express = require('express');


var app = express();

app.get('/hello', function(req, res){


res.send("Hello World!");
});

app.post('/hello', function(req, res){


res.send("You just called the post method at '/hello'!\n");
});

app.listen(3000);

To test this request, open up your terminal and use cURL to execute the following request:

curl -X POST "http://localhost:3000/hello"

A special method, all, is provided by Express to handle all types of http methods at a
particular route using the same function. To use this method, try the following.

app.all('/test', function(req, res){


12
ExpressJS

res.send("HTTP method doesn't have any effect on this route!");


});

This method is generally used for defining middleware, which we'll discuss in the middleware
chapter.

Routers
Defining routes like above is very tedious to maintain. To separate the routes from our main
index.js file, we will use Express.Router. Create a new file called things.js and type the
following in it.

var express = require('express');


var router = express.Router();
router.get('/', function(req, res){
res.send('GET route on things.');
});
router.post('/', function(req, res){
res.send('POST route on things.');
});
//export this router to use in our index.js
module.exports = router;

Now to use this router in our index.js, type in the following before the app.listen function
call.

var express = require('Express');


var app = express();

var things = require('./things.js');


//both index.js and things.js should be in same directory
app.use('/things', things);

app.listen(3000);

The app.use function call on route '/things' attaches the things router with this route. Now
whatever requests our app gets at the '/things', will be handled by our things.js router. The
'/' route in things.js is actually a subroute of '/things'. Visit localhost:3000/things/ and you
will see the following output.
13
ExpressJS

Routers are very helpful in separating concerns and keep relevant portions of our code
together. They help in building maintainable code. You should define your routes relating to
an entity in a single file and include it using the above method in your index.js file.

14
EXPRESSJS – HTTP METHODS ExpressJS

The HTTP method is supplied in the request and specifies the operation that the client has
requested. The following table lists the most used HTTP methods:

Method Description

The GET method requests a representation of the specified resource. Requests


GET
using GET should only retrieve data and should have no other effect.

The POST method requests that the server accept the data enclosed in the
POST
request as a new object/entity of the resource identified by the URI.

The PUT method requests that the server accept the data enclosed in the
PUT request as a modification to existing object identified by the URI. If it does not
exist then the PUT method should create one.

DELETE The DELETE method requests that the server delete the specified resource.

These are the most common HTTP methods. To learn more about the methods,
visit http://www.tutorialspoint.com/http/http_methods.htm.

15
ANGULAR

Unit-6
AngularJS
6.1.AngularJS Introduction:
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. It is licensed under the Apache license version 2.0.

Why to Learn AngularJS?

AngularJS is an open-source web application framework. It was originally developed in 2009


by Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest version is
1.2.21.
 AngularJS is a efficient framework that can create Rich Internet Applications (RIA).
 AngularJS provides developers an options to write client side applications using
JavaScript in a clean Model View Controller (MVC) way.
 Applications written in AngularJS are cross-browser compliant. AngularJS
automatically handles JavaScript code suitable for each browser.
 AngularJS is open source, completely free, and used by thousands of developers around
the world. It is licensed under the Apache license version 2.0.
Overall, AngularJS is a framework to build large scale, high-performance, and easyto-maintain
web applications.

K.SONI SHARMILA,CSE DEPT,SVECW


ANGULAR

Hello World using AngularJS.


Just to give you a little excitement about AngularJS, I'm going to give you a small conventional
AngularJS Hello World program.

<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>
Overall, AngularJS is a framework to build large scale, high-performance, and easyto-maintain
web applications.

6.2.What is SPA (Single page application) in AngularJS ?


Traditionally, applications were Multi-Page Applications (MPA) where with every click a
new page would be loaded from the server. This was not only time-consuming but also
increased the server load and made the website slower. AngularJS is a JavaScript-based
front-end web framework based on bidirectional UI data binding and is used to design
Single Page Applications. Single Page Applications are web applications that load a single
HTML page and only a part of the page instead of the entire page gets updated with every
click of the mouse. The page does not reload or transfer control to another page during the
process. This ensures high performance and loading pages faster. Most modern applications
use the concept of SPA. In the SPA, the whole data is sent to the client from the server at
the beginning. As the client clicks certain parts on the webpage, only the required part of
the information is fetched from the server and the page is rewritten dynamically. This
results in a lesser load on the server and is cost-efficient. SPAs use AJAX and HTML5 to
create fluid and responsive Web applications and most of the work happens on the client
side. Popular applications such as Facebook, Gmail, Twitter, Google Drive, Netflix, and
many more are examples of SPA.

K.SONI SHARMILA,CSE DEPT,SVECW


ANGULAR

Advantages of Single Page Application:


 Team collaboration: Single-page applications are excellent when more than one
developer is working on the same project. It allows backend developers to focus on the
API, while frontend developers can focus on creating the user interface based on the
backend API.
 Caching: The application sends a single request to the server and stores all the received
information in the cache. This proves beneficial when the client has poor network
connectivity.
 Fast and responsive: As only parts of the pages are loaded dynamically, it improves the
website’s speed.
 Debugging is easier: Debugging single-page applications with chrome is easier since
such applications are developed using AngularJS Batarang and React developer tools.
 Linear user experience: Browsing or navigating through the website is easy.
6.3.What is SPA Framework?
A single page web application framework is a web framework that provides a platform for
web app development of SPAs. These SPA frameworks incorporate a set of tools and
libraries for avoiding repetitive coding. In addition, they also support unit testing, automated
data binding, URL routing and HTML tag manipulation.

K.SONI SHARMILA,CSE DEPT,SVECW


ANGULAR

SPA frameworks have been steadily gaining popularity, especially for businesses and
startups. There are many advantages using single page application framework in your web
project-

Top 5 Single Page Application Frameworks

EmberJS

EmberJS is a single page application framework based on the JavaScript language. It is a


robust framework that comes inbuilt with a lot of functionalities that help you develop the
frontend of websites. Every EmberJS application works as a single page application.
AngularJS

AngularJS, developed by Google, is one of the oldest open-source JavaScript frameworks. It


is a multi-purpose framework, although many developers prefer AngularJS for developing
client-side applications.
ReactJS

ReactJS is a JavaScript library of UI components used for designing an interactive web app
interface. This library is often confused for a client-side framework because of the vast array
of features it offers.
BackBoneJS

BackboneJS is an ultra-lightweight JavaScript library that is used for developing client-side


applications on the web browser. It follows the MV* architecture, with Models and Views
to handle the user interface and the business logic code. The * stands for component handling
layer, but in BackboneJS the component logic is handled by the Views itself.

K.SONI SHARMILA,CSE DEPT,SVECW


ANGULAR

Vue

Vue is a popular progressive JavaScript framework used for developing high-performing web
applications and web interfaces.

6.4.MVC ARCHITECTURE
The Model

The model is responsible for managing application data. It responds to the request from view
and to the instructions from controller to update itself.

The View

A presentation of data in a particular format, triggered by the controller's decision to present


the data. They are script-based template systems such as JSP, ASP, PHP and very easy to
integrate with AJAX technology.

The Controller

The controller responds to user input and performs interactions on the data model objects. The
controller receives input, validates it, and then performs business operations that modify the
state of the data model.
AngularJS is a MVC based framework.

K.SONI SHARMILA,CSE DEPT,SVECW


ANGULAR

6.5.Getting Angular:
Installation Process of Angular CLI

To install the Angular CLI on your machine, open the terminal window and run the
following command:

npm install -g @angular/cli

where -g denotes that CLI is being installed globally to your machine, which means you can
create or run any command of CLI anywhere on your machine. Once you run the above
command CLI will be installed on your machine, and you can verify the version installed
using the following command:

ng version
Creating a Project using Angular CLI

Now, let’s create our first ever Angular project using Angular CLI. Open your terminal
window and type the command below on your machine.

ng new hello-world

K.SONI SHARMILA,CSE DEPT,SVECW


ANGULAR

After running this command you will find the full architecture of the project in the directory
where you run this command. The project folder will be something like below in the image
-

Run the following command on the terminal (Navigate to the project directory if you are not
in that directory).

ng serve

(or)or

ng serve --open
The --open (or just -o) option automatically opens your browser to
http://localhost:4200/. Accessing Angular Web Interface

ng serve command may take a few seconds to run your application, and once completed,
you should see a web page similar to the following.

K.SONI SHARMILA,CSE DEPT,SVECW


ANGULAR

AngularJS - First Application


Before creating actual Hello World ! application using AngularJS, let us see the parts of a
AngularJS application. An AngularJS application consists of following three important parts −
 ng-app − This directive defines and links an AngularJS application to HTML.
 ng-model − This directive binds the values of AngularJS application data to HTML
input controls.
 ng-bind − This directive binds the AngularJS Application data to HTML tags.

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.

K.SONI SHARMILA,CSE DEPT,SVECW


ANGULAR

<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.

6.6.DIRECTIVES

Directive Description

ng-app Auto bootstrap AngularJS application.

ng-init Initializes AngularJS variables

ng-model Binds HTML control's value to a property on the $scope object.

ng- Attaches the controller of MVC to the view.


controller

ng-bind Replaces the value of HTML control with the value of specified AngularJS expression.

ng-repeat Repeats HTML template once per each item in the specified collection.

K.SONI SHARMILA,CSE DEPT,SVECW


ANGULAR

6.7. controller
1. AngularJS controllers control the data of AngularJS applications.

2. AngularJS controllers are regular JavaScript Objects.

3. AngularJS applications are controlled by controllers.

4. The ng-controller directive defines the application controller.

5. A controller is a JavaScript Object, created by a standard JavaScript object


constructor.

K.SONI SHARMILA,CSE DEPT,SVECW


ANGULAR

6.8. Data binding or Two-way Binding

Data binding in AngularJS is the synchronization between the model and the
view.

When data in the model changes, the view reflects the change, and when
data in the view changes, the model is updated as well. This happens
immediately and automatically, which makes sure that the model and the
view is updated at all times.

K.SONI SHARMILA,CSE DEPT,SVECW


ANGULAR

6.9.Client Side Routing in Angular


In a traditional web application every request for displaying a page goes to the server and
results in a full page load. Whereas in a Single page application each request doesn’t go to the
server. Web server gives a single page, any further rendering is done locally by the Java
script. So, in a SPA you will get a single page and part of the page is updated dynamically for
further requests.
That is done by using selector like <app-root></app-root> and <router-outlet></router-
outlet>. Your components will be dynamically loaded with in the selector without causing a
full page load.
But this single page application behavior, where we don’t need to change the URL, raises
some questions-
How can you change the URL without causing a page reload.
How can we preserve the forward/back button behavior of the browser, since there is no URL
change so no states.
How to refresh a page.
Also from routing perspective how to map URLs to handling components.
That’s where client side routing is used to maintain and preserve states. Client side routing
changes the URL and also saves the state without making a server request.
Client side routing strategy
Client side routing gives your application ability to-
Change the URL in browser.
Push the state in history so that you can move back or forward
In Angular there is a routing module that provides this functionality out of the box. Angular
gives two options for handling client side routing.
Hash based routing
HTML5 routing
These two options are defined by the location strategy used by Angular, for Hash based
routing the corresponding location strategy is HashLocationStrategy whereas for HTML5
routing it is PathLocationStrategy.
You can read more about Location Strategies in this post- Location Strategies in Angular
Routing
Since HTML5 is supported by all modern browsers so mostly you'll be using
PathLocationStrategy and it is also the default location strategy in Angular.
The history.pushState method which is part of HTML5 allows you to push an entry to the
browser’s history object. The history.pushState method takes three parameters-
State object- For passing state data to the new history entry

K.SONI SHARMILA,CSE DEPT,SVECW


ANGULAR

Title- a title for the state


URL- A URL for the history entry.
Using history.pushState method you achieve the desirable features of client side routing-
Since new history entries are created so the URL also changes in the browser to reflect new
state.Since history entries are there so you can also use back and forward buttons in browser
to move back and forth.

6.10.Testing Angular:
Testing your Angular application helps you check that your application is working as you expect.

Prerequisites

Before writing tests for your Angular application, you should have a basic understanding of the
following concepts:
Angular fundamentals
JavaScript
HTML
CSS
Angular CLI

Set up testing
The Angular CLI downloads and installs everything you need to test an Angular application
with Jasmine testing framework.

The project you create with the CLI is immediately ready to test. Just run the ng test CLI
command:

ng test

The ng test command builds the application in watch mode, and launches the Karma test
runner.

The console output looks the below:

02 11 2022 09:08:28.605:INFO [karma-server]: Karma v6.4.1 server started at http://localhost:9876/


02 11 2022 09:08:28.607:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
02 11 2022 09:08:28.620:INFO [launcher]: Starting browser Chrome
02 11 2022 09:08:31.312:INFO [Chrome]: Connected on socket -LaEYvD2R7MdcS0-AAAB with id
31534482
Chrome: Executed 3 of 3 SUCCESS (0.193 secs / 0.172 secs)
TOTAL: 3 SUCCESS

K.SONI SHARMILA,CSE DEPT,SVECW


ANGULAR

The test output is displayed in the browser using Karma Jasmine HTML Reporter

K.SONI SHARMILA,CSE DEPT,SVECW

You might also like