0% found this document useful (0 votes)
16 views198 pages

Node Js

The document provides a comprehensive overview of Node.js, an open-source runtime environment for executing JavaScript outside the browser, including its installation, module system, and features. It covers various topics such as built-in, local, and third-party modules, the benefits of using Node.js for server-side applications, and the use of Nodemon for development. Additionally, it explains the Node.js lifecycle, including the roles of the V8 engine and libuv in handling asynchronous I/O.

Uploaded by

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

Node Js

The document provides a comprehensive overview of Node.js, an open-source runtime environment for executing JavaScript outside the browser, including its installation, module system, and features. It covers various topics such as built-in, local, and third-party modules, the benefits of using Node.js for server-side applications, and the use of Nodemon for development. Additionally, it explains the Node.js lifecycle, including the roles of the V8 engine and libuv in handling asynchronous I/O.

Uploaded by

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

NODEJS

Installing and Exploring NodeJS

6 Articles
Learn

Fundamentals

6 Articles
Learn

NodeJS Module System

3 Articles
Learn

HTTP Module

5 Articles
Learn

Async and Await

1 Article
Learn

Web Servers

3 Articles
Learn

MongoDB and Mongoose

7 Articles
Learn

API Auth and Security

6 Articles
Learn

Application Deployment

4 Articles
Learn

Mini Project

1 Article

Intro of NodeJS, Installing NodeJS

Node.js is an open-source and cross-platform runtime environment for executing


JavaScript code outside the browser. We often use Node.js for building back-end
services APIs like Web App or Mobile App. We don't build code for every single feature
of a major program from scratch. Instead, we focus on the main product and leverage
pre-built components provided by others or ourselves to support and enhance the
feature, which is referred to as modules.

Features of Node.js: There are other programming languages that can be used to
build back-end services so what makes Node.js different we are going to explain.

1. Node.js is a single threaded and built on an event-driven, non-blocking I/O


mechanism that makes Node applications extremely fast and scalable.
2. Node is ideal for creating data-intensive web apps that are both quick and
scalable.
3. Large ecosystem for open source library.
4. Source code cleaner and consistent.
5. It uses JavaScript everywhere, so it’s easy for a JavaScript programmer to build
back-end services using Node.js
6. APIs with databases, Data Streaming & server-side web apps, Real-time chat
applications, and more can all be built using Node.js.

Installation of Node.js on Windows: You need to download and install Node


into your local system in order to use Node and create web applications using
Node.js. To do so follow the below steps one by one:
Step 1: Go to the official Node website and download the latest Node.js ‘.msi’
installer from there. You'll find two versions over there LTS (recommended) and
Current. LTS is a stable version whereas Current is the beta release with the latest
features.

Step 2: Running the Node.js installer. Now you need to install the node.js installer
on your PC. You need to follow the following steps for the Node.js to be installed:

Double click on the .msi installer and the Node.js Setup Wizard will open, and click
on "Next".

After clicking “Next”, End-User License Agreement (EULA) will open. Check “I accept
the terms in the License Agreement” and Select “Next”
Set the Destination Folder where you want to install Node.js & Select "Next".

Select "Next" on Custom Setup.

You are all ready to install Node.js. Select "Install".


Do not close or cancel the installer until the installation is complete. Click “Finish” to
Complete the Node.js Setup Wizard.

Step 3: Verify that Node.js was properly installed or not.


To check whether node.js was completely installed on your system or not, write the
below code in the command prompt or any terminal:

node -v

If node.js is completely installed on your system, the command prompt will print the
version of the node.js installed as shown in the above image.

Understanding Node Modules


Node.js is an open-source and cross-platform runtime environment for executing
JavaScript code outside a browser. We often use Node.js for building back-end
services APIs like Web App or Mobile App. We don't build code for every single feature
of a major program from scratch. Instead, we focus on the main product and leverage
pre-built components provided by others or ourselves to support and enhance the
feature, which is referred to as modules.

Modules are the collection of functions that may be imported and utilized with
another program based on their related functionality. Modules can be grouped
together in one or more JavaScript files. It is a good practice to use modules because
of their reusability and ability to break down a large piece of code into components
and functions. That concept is called modularity.

In Node.js, npm (Node Package Manager) is the default package manager for Node.js.
It gets installed into the system with the installation of Node.js. The required packages
and modules in the Node project are installed using NPM. Node.js is famous because
of NPM which is currently the world's largest collection of packages of code with more
than 1 million packages or modules. To install any module with npm, simply write the
following code in the terminal:

npm install module_name

Here, module_name will be the name of the module that you want to install in your
Node.js application.

The modules in Node.js are mainly categorized into three types:

 Built-in Modules
 Local Modules
 Third-party Modules
Built-in Modules: When we install Node into the system, it comes with some of the
built-in modules that are part of the platform. These modules can be loaded into the
program by using the require function.

Syntax:

var module = require('module_name');

Example: It is a simple example that will demonstrate how to make a web server with
a Node.js HTTP module. Write the below code in the index.js file:

index.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('GeeksforGeeks!');
res.end();
}).listen(8080);

Steps to run the server: Write the below command in the terminal to run the
server:

node index.js

Output:

GeeksforGeeks!

In the above example, the require() function returns an object because the HTTP
module returns its functionality as an object. The function http.createServer() method
will be executed when someone tries to access the computer on port 8080. The
res.writeHead() method is the status code where 200 means it is OK, while the second
argument is an object containing the response headers.

The following list contains some of the important core modules in Node.js:

Core Description
Modules

assert Set of assertion functions useful for testing.

buffer Ability to handle buffers containing binary data.

crypto Used for cryptographic functionality.

fs Used to handle file system.

http Creates an HTTP server in Node.js

os Provides utility methods and characteristics for the operating system.

path Provides tools for manipulating file and directory paths.

process Provides information and control about the current Node.js process.

querystring The utility used for parsing and formatting URL query strings.

url The module provides utilities for URL resolution and parsing.

timers Provide functions for scheduling functions to be executed at a later time.

Local Modules: The modules that have been created by ourselves locally in your
Node.js application so that we can re-use that again as a component in the future by
using the required function.
Example: Let’s create a scenario where we have to print the name and designations
of employees. So in that case, we'll create a class of employees having that
information.

 index.js: This is the main code section where we'll use the Employee module
and give our dynamic data according to our needs:

index.js
const Employee = require('./employee.js');
const employee1 = new Employee('Gaurav', 'Freelancer');
const employee2 = new Employee('vaibhav', 'Graphics Designer');

employee1.info();
employee2.info();
 employee.js: This file contains the Local module that has create by you and
can be used in any Node.js application:

employee.js
class Employee {
constructor(name, des) {
this.name = name;
this.des = des;
}

info() {
console.log(`My name is ${this.name} and I am ${this.des}`);
}
}

module.exports = Employee;

Steps to run the server: Write the below command in the terminal to run the server

node index.js

Output:

My name is Gaurav and I am Freelancer


My name is Vaibhav and I am Graphics Designer

Third-party Modules: Third-party modules are available online using the Node
Package Manager(NPM). These modules can be installed in the project folder or
globally (-g). You can go to the NPM official website and search for your required
module from 1 million packages.

Example: Let's search for a module called "superheroes" and create a simple
application:

First, go to the NPM website and search for superheroes. You can now install that
module by writing the following code in the terminal:

npm i superheroes
Note: 'i' is also permitted to install single modules.

 index.js: Now, write the below code in the index.js file:

Javascript
var superheroes = require('superheroes');

var Name = superheroes.random();

console.log(Name);

Output:

In the above example, we are first importing the superheroes module by using
require() function. Then, we are printing the random hero names by calling the
random() method on the superheroes variable.
Some of the popular third-party modules are mongoose, express, angular, and react.
To install Third-party Modules, write the following command in the terminal:

npm install express


npm install mongoose
npm install -g @angular/cli

Running on a browser vs Running on a server

You have probably already used JavaScript before and it was probably always just
inside a browser because any browser natively understands HTML, CSS, and
JavaScript. But, thanks to modern technology, we can now use JavaScript in devices
such as smartwatches, light bulbs, drones, and servers, all of which are made feasible
by the JS runtime environment.

We can run JavaScript on a server through the medium Node.js when we take
JavaScript out of the browser and just execute or run JavaScript code somewhere else
without all of the restrictions that we have in the browser. It's just another JavaScript
runtime that allows you to run JavaScript code outside of a browser.

To understand how javascript works in the browser and on the server, you must first
understand what the JS runtime environment is and how it functions.
JavaScript Runtime Environment: The JavaScript Runtime Environment is similar
to a large container that contains everything needed to run JavaScript code, such as
the JavaScript Engine, Web APIs, Event Loop, Callback queue, and microtask queue.

The core component of the JS Runtime Environment is the JS Engine. The JS Engine
receives code as input and performs three key tasks: parsing, compilation, and
execution. The call stack is where all of the javascript code is performed. The event
loop executes each function in the callback queue one by one. Local storage, console,
DOM, Timeout functions, Bluetooth, geolocation, and other features are accessed via
Web APIs.

Running on a browser: A web Browser is an Application program that displays a


World wide web document. It usually uses the internet service to access the
document. The browsers also have their own JavaScript Runtime Environment, which
allows JavaScript code to be run within the browser. With HTML and Javascript, we can
develop dynamic websites that interact with the DOM (web API), add functionality to
the code, and provide animations, among other things. However, we can't build a web
application using simply Javascript in the browser.

Running on a Server: A web server is a program or computer that provide services


to other programs called client. Now that we have JavaScript outside of the browser,
in a kind of standalone environment that is just Node.js. Node is the open-source and
cross-platform runtime environment for executing JavaScript code outside of a
browser, based on Chrome's V8 JavaScript engine., we can do a lot more with JS that
was previously impossible, such as accessing files systems and having better
networking capabilities.

Benefits of Running JavaScript on the server:

 Node applications are so fast and scalable because Node.js is a single-threaded


based on an event-driven, non-blocking I/O model.
 Node is ideal for creating data-intensive web apps that are both quick and
scalable.
 With the help of Node.js, we may create APIs for databases.
 Node is ideal for creating data streaming applications like Netflix, Youtube, and
Hotstart.

Note: Applications with heavy server-side processing (CPU intensive) like image
manipulation, video comparison, file compression, etc are not good to build with
Node.

Nodemon

Nodemon is a module that you can use with your node.js programs, especially if
you're developing things like web servers and want to save and restart them as you
make changes, which can be a hassle if you're doing it frequently. Nodemon does not
require any change in the original code and method of development.

How to Install nodemon: We can install nodemon once on the system and then
utilize it in all node.js applications. Type the following command in the terminal to
install nodemon on your system:

npm install -g nodemon

Here, the -g flag is an indication that we want to install nodemon globally into our
system.

You may verify the current version of the nodemon after installing the module by
executing the following command:

nodemon --version

Using Nodemon: Using the nodemon is as easy as using the node command to run
the application. We have to write 'nodemon' instead of 'node' and then mention the
filename to start the server as shown below:

nodemon [filename]

Example: This is a basic example to demonstrate the use nodemon. In the index.js
file, write the following code:

index.js

var http = require('http');


http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('Welcome to this page!');
res.end();
}).listen(3000);

Steps to start the application: Write the below code to start the server through
nodemon:

nodemon index.js

Output:

Welcome to this page!

Now, suppose you change something in code and saved it, nodemon will
automatically detect the change and restart the server to render the new version of
the application. In this case, let's change the text as res.write('GeeksforGeeks!'), the
output will change as:

GeeksforGeeks!

Note: You can manually restart the nodemon server by typing 'rs' in the terminal
while running nodemon command.
Node Life Cycle

Node.js is a JavaScript runtime based on Chrome's V8 JavaScript engine, and its run-
time environment contains everything required to run a JavaScript program. The
architecture in terms of Node's dependencies, which are only a number of libraries
that Node need to function properly. So the Node run time has several dependencies
and the most important ones are the V8 JavaScript engine and Libuv.
The V8 engine is responsible for converting JavaScript code into machine code that a
computer can understand, but it is insufficient to develop a complete server-side
framework like Node.js. As a result, libuv is likewise included in Node.

Libuv is a free and open-source library that focuses on asynchronous I/O. This layer
offers Node access to the computer's underlying operating system, file system,
networking, and other features. Aside from that, libuv supports two crucial Node.js
features: the Event Loop and the Thread Pool.

Note: V8 and libuv aren't the only libraries used by Node; it also uses http-parser for
HTTP parsing, c-ares for DNS requests, OpenSSL for cryptography, and zlib for
compression.

Lifecycle of Node.js: In order to understand its lifecycle you must be familiar with
the thread pool and event loop. After the program has been initialized, all of the code
has been executed, and all of the modules have been installed, the event loop can
finally begin to run.

 Thread pool: Node executes in a single thread. Some tasks are simply too
difficult. They're too expensive to run in the event loop because they'd lock up
the single thread. That's where the thread pool comes in, which, like the event
loop, is provided by the Libuv package to Node.js. The thread pool provides us
with four other threads that are fully independent of the main thread. And we
can actually configure it up to 128 threads. As a result, these threads formed a
thread pool, which the event loop can use to offload costly activities like file
system API, cryptography, compression, DNS lookups, and so on.
 Event Loop: The event loop executes all of the application code included within
the callback function. Basically, the event loop will run all code that isn't top-
level code. It's the nucleus of the Node architecture. Things like an application
receiving an HTTP request on our server, a timer expiring, or a file concluding to
read will all emit events once they've completed their tasks, and our event loop
will gather them up and perform the callback function associated with each
event.
Jav
ascript
const http = require('http');
const server = http.createServer(function (req, res) {

console.log("server is running");
process.exit();
});

server.listen(8000);
Explanation: In the above program inside the createServer() method, you have
written simply process..exit() so as soon as you will run this program using the node
app your server will wait for listening to your request and once you will provide it with
the request it will exit from the event loop. By calling this function, Node.js will force
the current process which is currently running to abort as soon as possible and if there
are any asynchronous operations taking place, they will also be terminated
immediately.

Backend v/s Frontend

Frontend and Backend are the two most popular terms used in web development.
These terms are very crucial for web development but are quite different from each
other. Each side needs to communicate and operate effectively with the other as a
single unit to improve the website’s functionality.

Front End Development: Everything that occurs in the web browser is referred to
as frontend development. As a result, the name front-end refers to the process of
planning and developing the final website that will be visible to users.
The front-end technology stack includes HTML, CSS, and Javascript, which are used in
front-end development. Many current front-end developers now add additional
components to the front-end stack, such as React or Angular, Redux or GraphQL, and
so on. So these technologies make front-end development easier, and the front-end
stack is the collection of technologies that a developer or team chooses to employ on
the front end.

Front end Languages: The front end portion is built by using some Languages
which are discussed below:

 HTML: HTML stands for Hypertext Markup Language. It is used to design the
front-end portion of web pages using a markup language. HTML is the
combination of Hypertext and Markup language. Hypertext defines the link
between the web pages. The markup language is used to define the text
documentation within the tag which defines the structure of web pages.
 CSS: Cascading Style Sheets fondly referred to as CSS is a simply designed
language intended to simplify the process of making web pages presentable.
CSS allows you to apply styles to web pages. More importantly, CSS enables you
to do this independent of the HTML that makes up each web page.
 JavaScript: JavaScript is a famous scripting language used to create magic on
the sites to make the site interactive for the user. It is used to enhance the
functionality of a website to run cool games and web-based software.

Back End Development: The back-end of web development refers to everything


that occurs on the webserver or everything that is not visible to the end-user,
therefore the name back-end.
Now that we're on the subject of the server-side, let's define what a server is. Well, a
basic server is actually just a computer linked to the internet that first stores a
website's files, such as HTML, CSS, and graphics, and then run the HTTP server, which
can recognize URLs and respond to requests. This piece of HTTP server software is
what uses requests and responses to connect with the browser. As a result, it's similar
to bridging the gap between a website's front-end and back-end.

A simple web server, such as the one just described is referred to as a static server
because that can provide static files to the clients via HTTP. If you just need to host a
simple website, this is all you need. However, if you want to take it a step further and
construct dynamic web applications that interact with databases and other such
features, you'll need a server that can also run dynamic applications. This is referred
to be a dynamic server, because we have an application running an HTTP server, and
the files are all communicating with one another.

We commonly use a database while creating a dynamic website or application, which


we can access directly from our applications. Node.js can be used as a dynamic web
server, and MongoDB is the most popular database for Node.

Create user profiles, execute log-ins, send emails, handle payment, obtain and deliver
request data from a database to a client, alter data in the database, fill up website
templates, and so much more are all handled on the back-end or server-side.
Back end Languages: The back end portion is built by using some languages which
are discussed below:

 PHP: PHP is a server-side scripting language designed specifically for web


development. Since PHP code is executed on the server-side, so it is called a
server-side scripting language.
 C++: It is a general-purpose programming language and is widely used
nowadays for competitive programming. It is also used as a backend language.
 Java: Java is one of the most popular and widely used programming languages
and platforms. It is highly scalable. Java components are easily available.
 Python: Python is a programming language that lets you work quickly and
integrate systems more efficiently.
 JavaScript: JavaScript can be used as both (front end and back end)
programming languages.
 Node.js: Node.js is an open-source and cross-platform runtime environment for
executing JavaScript code outside a browser. You need to remember that
NodeJS is not a framework, and it’s not a programming language. Most people
are confused and understand it’s a framework or a programming language. We
often use Node.js for building back-end services like APIs like Web App or Mobile
App. It’s used in production by large companies such as Paypal, Uber, Netflix,
Walmart, and so on.

You've probably heard of the term "full-stack," which refers to both the front-end and
back-end stacks combined. So, a full stack developer is someone who works on both
the front-end and the back-end, but these developers are becoming increasingly rare,
especially as the front-end becomes increasingly complicated.

Sync v/s Asynchronous

Synchronous: Synchronous code will begin at the top of a file and execute its way
down to the bottom, executing each line in turn until it reaches the end. Simply put,
synchronous means the code is running line by line, in the exact sequence that we
specify in our code.

As soon as the first line of code is accessed during execution, it is simply executed
during the thread's execution. The thread's execution is part of the execution context,
which is actually responsible for executing the code in the computer's processor. Then
the next line of code is run, and the next, and so on, in order. As a result, each line of
code always waits for the previous line to complete execution before continuing.
Example: This is a simple example that will demonstrate the working of synchronous
programming:

HTML
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<h2 class="text"></h2>

<script>
console.log('First line of code');
const text = document.querySelector('.text');
text.textContent = "GeeksforGeeks";
alert('Click OK to proceed further!!');
text.style.color = "green";
console.log('Color Changed');
</script>

</body>

</html>

Output:
Explanation: In the script tag, We have an alert statement in this line of code, which
creates an alert window that can prevent the code from running. So, until we click the
OK button, nothing will happen on the page, and only then will the code be able to
continue running. As a result, it first printed "First line of code" in the console,
followed by an alert window. It waited until the OK button was pressed before
proceeding to convert the text color to green.

Now, this can create problems when one line of code takes a long time to run. For
example for a five-second timer to finish, that would block the content of the page,
and that is where the asynchronous comes into play.

Asynchronous: Asynchronous code allows the program to be executed immediately


where the synchronous code will block further execution of the remaining code until it
finishes the current one. This may not look like a big problem but when you see it in
the bigger picture you realize that it may lead to delaying the User Interface.

Example: This is the same example as before, but the code has been updated to
explain the working of asynchronous programming:

HTML
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<h2 class="text"></h2>

<script>
console.log('First line of code');
const text = document.querySelector('.text');
text.textContent = "GeeksforGeeks";
setTimeout(function () {
text.style.color = "green";
}, 3000);
console.log('Color Changed');
</script>

</body>

</html>

Output:
Explanation: In the script tag, the first line of code is still synchronous, and it goes to
the second line in the same manner, but now it comes across the setTimeout method,
which will start an asynchronous timer. As a result, the timer will essentially operate
in the background without interfering with the main code. As a result, the console will
first display "First line of code," followed by the timer, which is set for 3 seconds.
Meanwhile, the code will continue on to the remaining line and output "Color
Changed," despite the fact that the color has not changed. The color will likewise
change after 3 seconds.

Async Callbacks

Asynchronous code allows the program to be executed immediately whereas the


synchronous code will block further execution of the remaining code until it finishes
the current one. This may not look like a big problem but when you see it in the bigger
picture you will realize that it may lead to delaying the User Interface.

Asynchronous callback functions, such as setTimeout(), are used. It is asynchronous


because it will only be executed when a background task has been completed.
However, this does not imply that callback functions make code asynchronous by
default. The array map() method, takes a callback function, but this does not make
the code asynchronous. Only a few functions, such as setTimeout() can be used
asynchronously.

Callback: A callback is a function that is called when a task is completed, thus


helping in preventing any kind of blocking and a callback function allows other code to
run in the meantime. The callback is called when the task gets completed and is the
asynchronous equivalent to a function. Callbacks are an excellent approach to deal
with something after it has been accomplished. By something here we mean a
function execution. If we want to execute a function right after the return of some
other function, then callbacks can be used.
Note: Callback functions alone do not make code asynchronous.

Example 1: The following JavaScript code demonstrates how callbacks work:

Javascript
function sum(first, second, callback) {
console.log(`The sum of ${first} and ${second}
is ${first + second}.`);
callback();
}

function disp() {
console.log('This must be printed after addition');
}

sum(5, 6, disp);

Output:

Explanation: This may be seen in the code above. There is a sum() function that
accepts three arguments. The first two attributes are integer values, while the last
attribute is the disp() function, which acts as a callback() function that can only be
executed when called. As a result, the sum() function displays the sum of two
numbers in the console before calling the callback function, which is only reported
after the addition because it is called in this manner.
Example 2: The following JavaScript code demonstrates how callbacks work:

Javascript
setTimeout(function () {
console.log("GeeksforGeeks");
}, 3000);

function first(second) {
console.log("This is the body of first function");
second();
}

function second() {
console.log("This is the body of second function");
}

console.log("Welcome to the course.");

first(second);

Output:
Explanation: The setTimeout() method is at the head of the list, followed by the
first() and second() functions, and finally the console.log function(). However, because
there is a timer set for 3 seconds, the code will read the setTimeout() method and
hold it in the callback queue. Then there are two functions that are defined but not yet
called. So first it prints the console log, then it calls the first() function, which takes
the second function as an argument, and last it calls the second() function. In the
meantime, the setTimeout() function will wait 3 seconds before executing.

Blocking v/s Non-blocking

Node.js is a single-threaded programming language with a non-blocking event-driven


I/O model. In this article, we will discuss what Blocking and Non-Blocking in Node.js
mean. For that, we first know what is synchronous and asynchronous code.

Synchronous simply means that each sentence is processed line by line, one after the
other. Synchronous code will begin at the top of a file and execute its way down to the
bottom, executing each line in turn until it reaches the end.

Blocking: It refers to the blocking of further operations until the current operation
finishes. Blocking methods are executed synchronously. Synchronously means that
the program is executed line by line. The program waits until the called function or
the operation returns.

Example: The below example will help to understand the concept of blocking code in
Node.js:

Javascript
const fs = require('fs');
const geeks = fs.readFileSync('geeks.txt', 'utf-8');
console.log(geeks);

console.log("\n We are getting the file data, please wait...");


Output:

Explanation: The file system module is first required in this example, after which the
file is read, the result is logged to the console, and lastly the string "We are getting
the file data, please wait..." is displayed, which should be executed while the file is
reading data. As you can see, each line of code essentially awaits the outcome of the
previous line.

This can be an issue, especially when doing lengthy activities like reading a large file
because each line prevents the rest of the code from running. As a result,
synchronous code is also known as blocking code since one operation can only be
performed after the previous one has been completed. As a result, in node.js, the
approach is to employ asynchronous, non-blocking code.

As a result, in asynchronous programming, we outsource the hard lifting to the


background. Then, once that job is completed, the result is handled by a callback
function that we previously registered. And the remainder of the code can continue to
run during this period without being slowed down by the hefty task that is now
running in the background.
Non-Blocking: It refers to the program that does not block the execution of further
operations. Non-Blocking methods are executed asynchronously. Asynchronously is
just the opposite of Synchronous, where the program may not always run line by line.
The program calls the function and moves to the next operation and does not wait for
it to return.

Example: The below example will help to understand the concept of Non-blocking
code in Node.js:

Javascript
const fs = require('fs');
fs.readFile('geeks.txt', 'utf-8', function (err, data) {
console.log(data)
});

console.log('We are getting the file data, please wait...\n');

Output:

Explanation: We utilized the asynchronous readFile() function in this example, which


accepts a callback function. This will begin reading the file in the background before
moving on to the following statement, which will print the string "We are getting the
file data, please wait..." to the console. So code execution will not be halted here;
instead, when the file has been entirely read, the callback function will be invoked,
and the data read will be reported to the console.

Why Node.js is non-blocking whereas JavaScript is blocking?

There is just one thread in the Node.js process, which is where our application is
operating, and a thread is a series of instructions that run in the computer's CPU. In a
nutshell, the thread is where our code is actually executed in the processor of a
machine.

Because Node.js is single-threaded, each application has only one thread. That means
every user who accesses your program is using the same thread. As a result,
whenever users interact with the application, the code that is run for each user is run
in the same thread and in the same location on the computer that is running the
application.

Now, it means that when one user blocks the single thread with sync code, then all
other users will have to wait for that execution to finish and that might not be a huge
problem for 10 users, but it definitely will for thousands of users at the same time.
Now, if one user uses synchronous code to block a single thread, all other users will
have to wait for that execution to complete, which may not be a big deal for ten users,
but it will be a big deal for thousands of users at the same time.
Blocking

T1 in the above figure could be a large file reading, database query, or anything else
that takes so long. Meanwhile, all other tasks T2, T3, and T4 in the image are waiting
for the call stack to empty which makes the Node.js Blocking.

Assume a user is accessing your application, and the code reads a large sync file that
will take 1 second to load. This means that all other users will have to wait in the
interim because the entire execution will be halted for that one second. As a result, if
the other user wants to perform anything as easy as or request some data, they won't
be able to. They'll have to wait till the file is finished reading before they can do
anything. Only then will they be able to complete the simple tasks one by one.
Non-Blocking

T1 is loading in the thread pool side by side in this figure, and it is not blocking the
call stack. So T2, T3, and T4 will be able to simply execute one after the other, and T1
will execute in the end after successful loading which makes the Node.js Non-
blocking.

So, in the identical situation, asynchronous, instead of blocking a single thread, does
the heavy lifting in the background, where it essentially stays until the data from the
file is read. We also register a callback function that will be triggered once the data is
accessible so that all other users can do their jobs in a single thread, one after the
other, while the file is still being read in the background. Our callback function will
now be invoked after the data has been read, and it will be executed in the main
single thread to handle the read data.

Multi Threading, Process and Threads


Node.js is a JavaScript runtime based on Chrome's V8 JavaScript engine, and its run-
time environment contains everything required to run a JavaScript program. When we
run a Node.js program on a computer, there is a Node process that starts which is
just a program in execution.

Process: It is basically the programs that are dispatched from the ready state and
are scheduled in the CPU for execution.

Thread: It is the segment of a process that means a process can have multiple
threads and these multiple threads are contained within a process. A thread has three
states: Running, Ready, and Blocked.

Multithreading: It is a system in which multiple threads are created in a process for


increasing the computing speed of the system. In multithreading, many threads of a
process are executed simultaneously and process creation in multithreading is done
according to economics.

How do Process and Threads work in Node.js?

Node.js runs in a single thread in that process. And a thread is nothing but a series of
instructions. Node runs in a single thread, making it simple to block Node apps,
whether you have ten or ten million people accessing it at the same time. As a result,
you must use extreme caution in order to avoid blocking that thread.
When you start your Node application and it's initialized, all of the top-level code, that
is, code that isn't within any callback function gets run. All of the modules that your
application requires are also necessary, as are all of the callbacks. The event loop
then begins to operate after all of this.

Some tasks are simply too difficult. They're too expensive to run in the event loop
because they'd lock up the single thread. That's where the thread pool comes in,
which, like the event loop, is provided by the Libuv package to Node.js. The thread
pool provides us with four other threads that are fully independent of the main thread.
And we can actually configure it up to 128 threads. As a result, these threads formed
a thread pool, which the event loop can use to offload costly activities like file system
API, cryptography, compression, DNS lookups, and so on.

Node.js Worker Threads: Worker Threads in Node.js is useful for performing heavy
JavaScript tasks. With the help of threads, Worker makes it easy to run javascript
codes in parallel making it much faster and more efficient. We can do heavy tasks
without even disturbing the main thread. Worker threads were not introduced in the
older versions of Node. Therefore first update your Node.js for getting started.
Example: The below example is a simple demonstration of using Worker Thread in
Node.js.

worker.js: This file contains the code for the worker.js file:

worker.js
const { workerData, parentPort }
= require('worker_threads')

console.log('Welcome to the '


+ workerData);

parentPort.postMessage(
{ fileName: workerData, status: 'Done' })

index.js: This is the main file that contains the code for the index.js file:

index.js
const { Worker } = require('worker_threads')

function runService(workerData) {
return new Promise((resolve, reject) => {
const worker = new Worker(
'./worker.js', { workerData });
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0)
reject(new Error(
`The exit code was used to stop the Worker Thread: ${code}`));
})
})
}

async function run() {


const result = await runService('GeeksForGeeks')
console.log(result);
}

run().catch(err => console.error(err))

Step to run this application: Write the below command in the terminal to run the
server:

node index.js

Output:

Welcome to the GeeksForGeeks


{ fileName: 'GeeksForGeeks', status: 'Done' }

Explanation: Worker Thread has the workerData and parentPort. The workerData is
used to get data from the thread, while the parentPort is used to manipulate it. The
postMessage() method takes the filename fetched by worker data and uses it to post
the provided message in the console.

The runService() function returns a Promise and starts the worker thread. The function
run() is used to invoke the runService() method and provide the value for workerData.
Event Loop

Node.js is a single-threaded programming language with a non-blocking event-driven


I/O model. Node.js is memory-efficient because of these features. Despite the fact that
JavaScript is single-threaded, the event loop allows Node.js to conduct non-blocking
I/O operations.

The event loop executes all of the application code included within the callback
function. Basically, the event loop will run all code that isn't top-level code. The
callback function is at the heart of Node.js. As a result, functions are called when a
task is completed in the future. Because Node.js is based on an event-driven design, it
functions this way.

Things like an application receiving an HTTP request on our server, a timer expiring,
or a file concluding to read will all emit events once they've completed their tasks,
and our event loop will pick them up and perform the callback functions associated
with each event.

Features of Event-Driven Architecture:

 Events are emitted.


 Event loop picks them up.
 Callbacks are called.

Working of Event Loop: When Node.js starts, it initializes the event loop, processes
provided input script which may make async API calls, schedule timers, then begins
processing the event loop.
When using Node.js, a special library module called libuv is used to perform async
operations. This library is also used, together with the back logic of Node to manage a
special thread pool called the libuv thread pool. This thread pool is composed of four
threads used to delegate operations that are too heavy for the event loop. I/O
operations, Opening and closing connections, setTimeouts are examples of such
operations.

When the thread pool completes a task, a callback function is called which handles
the error (if any) or does some other operation. This callback function is sent to the
event queue. When the call stack is empty, the event goes through the event queue
and sends the callback to the call stack.

Phases of Event Loop: Each of the four major stages of the event loop has a
callback queue, which contains callbacks from the events that the event loop
receives. Let's go over each of the four phases one by one:

Phase 1: Expired Timer Callbacks: Callbacks from expired timers are handled in
the first phase. For example - setTimeout. If there are any callback functions from
timers that have recently expired, the event loop will handle them first. If a timer
expires while one of the other phases is being processed, the timer's callback will only
be executed after the event loop returns to the initial phase.

Each queue's callbacks are processed one by one until there are no more in the
queue, at which point the event loop moves on to the next phase.

Phase 2: I/O Polling and Callbacks: The second phase includes I/O polling and
callback execution. Polling is the process of searching for new I/O events that are
ready to be handled and adding them to a callback queue.

Phase 3: setImmediate Callbacks: This phase is for setImmediate callbacks, which


is a specific type of timer that we can use if we want to process callbacks right after
the I/O polling and execution phases, which is useful in some more complex use
cases.

Phase 4: Close Callbacks: Finally, close callbacks are handled in the fourth phase.
All closing events are processed in this phase. For instance, when a web server or a
WebSocket terminates.

There are actually two more queues besides these four callback queues:
the nextTick() queue and the other microtasks queue, which is primarily used for
resolved promises. If any callbacks are waiting to be processed in one of these two
queues, they will be executed immediately once the current phase of the event loop
has been completed, rather than waiting for the entire loop to complete.
And with that, we've completed the event loop's one tick, which is simply one cycle in
this loop. Now it's time to decide whether the loop should continue to the next tick or
the program should be terminated.

Node.js merely checks whether any timers or I/O activities are still running in the
background, and if none are, the program is exited. If there are any pending timers or
I/O operations, however, the event loop will continue to run and the next tick will
begin.

Task Queue and Micro Task Queue

To know the difference between Callback Queue and Microtask Queue, we need to
have a clear idea of how asynchronous JavaScript gets executed and what are the
roles that Callback Queue and Microtask Queue play.

Asynchronous code allows the program to be executed immediately, whereas the


synchronous code will block further execution of the remaining code until it finishes
the current one. This may not look like a big problem, but when you see it in the
bigger picture you realize that it may lead to delaying the User Interface.
Asynchronous callback functions, such as setTimeout(), are used. It is asynchronous
because it will only be executed when a background task has been completed.

A callback is a function that is called when a task is completed, thus helping in


preventing any kind of blocking, and a callback function allows other code to run in
the meantime. The callback is called when the task gets completed and is the
asynchronous equivalent to a function.
The major component that helps push callback functions from the callback queue or
microtask queue to the call stack is the event loop.

Event Loop: When using Node.js, a special library module called libuv is used to
perform async operations. This library is also used, together with the back logic of
Node, to manage a special thread pool called the libuv thread pool. This thread pool is
composed of four threads used to delegate operations that are too heavy for the
event loop. I/O operations, Opening and closing connections, setTimeouts are
examples of such operations.

When the thread pool completes a task, a callback function is called which handles
the error(if any) or does some other operation. This callback function is sent to the
event queue. When the call stack is empty, the event goes through the event queue
and sends the callback to the call stack.
Task Queue: Task Queue, also known as callback queue. After the timer gets
expired, the callback function is put inside the Callback Queue, and the Event Loop
checks if the Call Stack is empty and if empty, pushes the callback function from
Callback Queue to Call Stack and the callback function gets removed from the
Callback Queue. Then the Call Stack creates an Execution Context and executes it.

Example: This is a simple demonstration of the task queue or callback queue:

Javascript
console.log("Hey There");

setTimeout(() => {
console.log("Welcome to GeeksforGeeks");
}, 3000);

console.log("End of Line");

Steps to run the server: Write the below command in the terminal to run the
server:

node index.js

Output:

Hey There
End of Line
Welcome to GeeksforGeeks
Explanation: First, Global Execution Context will be present in the call stack, which
will run through each line one by one and push the callback functions into the callback
queue, as well as console the text to the display. As the first line of the code, it will
display the string "Hey There". Parallelly, The program will then wait 3 seconds for the
setTimeout function to complete, meanwhile, it will execute to the next line and show
the string "End of Line." After the 3 seconds have been completed, it'll push that
function into the callback queue also. Event Loop will check if the call stack is empty,
if so, it'll then push the timer to the call stack and execute.

Micro Task Queue: The Microtask Queue is identical to the Callback Queue in
appearance, but it has a higher priority. Functions in the microtask queue will be
executed first, whereas functions in the callback queue will be executed later.

The callback functions coming through Promises and Mutation Observer will go inside
the Microtask Queue. For example, in the case of .fetch(), the callback function gets to
the Microtask Queue. Promise handling always has a higher priority so the JavaScript
engine executes all the tasks from Microtask Queue and then moves to the Callback
Queue. When the call stack is empty, the event loop executes the callback function
from the callback queue and the microtask from the microtask queue.

Callback Queue Microtask Queue

Callback Queue gets the ordinary callback Microtask Queue gets the callback functions
functions coming from the setTimeout() API coming through Promises and Mutation
after the timer expires. Observer.

Callback Queue has a lesser priority than Microtask queue has a higher priority than the
Microtask Queue of fetching the callback Callback Queue for fetching the callback
functions to Event Loop. functions to Event Loop.

Importing NodeJS core Modules


Node.js is an open-source and cross-platform runtime environment for executing
JavaScript code outside the browser. We often use Node.js for building back-end
services APIs like Web App or Mobile App. We don't build code for every single feature
of a major program from scratch. Instead, we focus on the main product and leverage
pre-built components provided by others or ourselves to support and enhance the
feature, which is referred to as modules.

Modules are the collection of functions that may be imported and utilized with
another program based on their related functionality. Modules can be grouped
together in one or more JavaScript files. It is a good practice to use modules because
of their reusability and ability to break down a large piece of code into components
and functions. That concept is called modularity.

Core Modules: When we install Node into the system, it comes with some of the
built-in modules that are part of the platform. These modules can be loaded into the
program by using the require function. The require() function will return a JavaScript
type depending on what the particular module returns. The following example
demonstrates how to use the Node.js http module to create a web server.

Syntax:

var module = require('module_name');

Example 1: It is a simple example that will demonstrate how to make a web server
with a Node.js HTTP module. Write the below code in the index.js file:

Javascript
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('GeeksforGeeks!');
res.end();
}).listen(8080);

Steps to run the server: Write the below command in the terminal to run the
server:

node index.js

Output:

GeeksforGeeks!

In the above example, the require() function returns an object because the HTTP
module returns its functionality as an object. The function http.createServer() method
will be executed when someone tries to access the computer on port 8080. The
res.writeHead() method is the status code where 200 means it is OK, while the second
argument is an object containing the response headers.

Example 2: This is another example that will demonstrate how to fs module to


handle file system. Write the below code in the index.js file:

Javascript
const fs = require('fs');
fs.readFile('geeks.txt', 'utf-8', function (err, data) {
console.log(data)
});
console.log('We are getting the file data, please wait...\n');

Steps to run the server: Write the below command in the terminal to run the
server:

node index.js

Output:

In the above example, the require() function imports the module of file system into
the program. readFile() function helps to get access of the data from the file. It
accepts three arguments filename, encoding and, callback_function. Here, "geeks.txt"
must be a file into the local stogare which is get accessed by the readFile() function
and then console to the screen.

The following list contains some of the important core modules in Node.js:

Core Description
Modules

assert Set of assertion functions useful for testing.

buffer Ability to handle buffers containing binary data.

crypto Used for cryptographic functionality.

fs Used to handle file system.

http Creates an HTTP server in Node.js

os Provides utility methods and characteristics for the operating system.

path Provides tools for manipulating file and directory paths.

process Provides information and control about the current Node.js process.

querystring The utility used for parsing and formatting URL query strings.

url The module provides utilities for URL resolution and parsing.

timers Provide functions for scheduling functions to be executed at a later time.

Importing Own Files

Node.js is an open-source and cross-platform runtime environment for executing


JavaScript code outside a browser. We often use Node.js for building back-end
services APIs like Web App or Mobile App. We don't build code for every single feature
of a major program from scratch. Instead, we focus on the main product and leverage
pre-built components provided by others or ourselves to support and enhance the
feature, which is referred to as modules.

Modules are the collection of functions that may be imported and utilized with
another program based on their related functionality. Modules can be grouped
together in one or more JavaScript files. It is a good practice to use modules because
of their reusability and ability to break down a large piece of code into components
and functions. That concept is called modularity.
Local Modules: Putting all your code in a single file is not a good idea. The modules
that have been created by ourselves locally in your Node.js application so that we can
re-use that again as a component in the future by using the required function.

Exporting from files: Firstly we need to create a file called utils.js. Now We can
export javascript code written on this file using module.exports. In below a function is
defined and assigned to the module.exports.

Example 1: Let’s create a scenario where we have to print the name and
designations of employees. So in that case, we'll create a class of employees having
that information.

Index.js: This is the main code section where we'll use the Employee module and
give our dynamic data according to our needs:

Javascript
const Employee = require('./employee.js');
const employee1 = new Employee('Gaurav', 'Freelancer');
const employee2 = new Employee('vaibhav', 'Graphics Designer');

employee1.info();
employee2.info();
Employee.js: This file contains the Local module that has created by you and can be
used in any Node.js application:

Javascript
class Employee {
constructor(name, des) {
this.name = name;
this.des = des;
}

info() {
console.log(`My name is ${this.name} and I am ${this.des}`);
}
}

module.exports = Employee;

Steps to run the server: Write the below command in the terminal to run the
server:

node index.js

Output:

My name is Gaurav and I am Freelancer


My name is Vaibhav and I am Graphics Designer

Example 2: In this example, Let’s create a scenario where we have to print the name
and designations of employees. So in that case, we'll create a class of employees
having that information.
Index.js: This is the main code section where we'll use the Car module and give our
dynamic data according to our needs:

Javascript
const Car = require('./Car.js');
const Car1 = new Car('Mini Cooper', 'Chilli Red');
const Car2 = new Car('Porsche 718', 'Polar White');
const Car3 = new Car('Lamborghini Aventdor SVJ', 'Glossy black');

Car1.info();
Car2.info();
Car3.info();

Car.js: This file contains the Local module that has created by you and can be used in
any Node.js application:

Javascript
class Car {
constructor(name, color) {
this.name = name;
this.color = color;
}

info() {
console.log(`This is a ${this.color}
accented ${this.name}`);
}
}

module.exports = Car;
Steps to run the server: Write the below command in the terminal to run the
server:

node index.js

Output:

This is a Chilli Red accented Mini Cooper


This is a Polar White accented Porsche 718
This is a Glossy black accented Lamborghini Aventdor SVJ

Importing npm Modules

Node.js is an open-source and cross-platform runtime environment for executing


JavaScript code outside a browser. We often use Node.js for building back-end
services APIs like Web App or Mobile App. We don't build code for every single feature
of a major program from scratch. Instead, we focus on the main product and leverage
pre-built components provided by others or ourselves to support and enhance the
feature, which is referred to as modules.

Modules are the collection of functions that may be imported and utilized with
another program based on their related functionality. Modules can be grouped
together in one or more JavaScript files. It is a good practice to use modules because
of their reusability and ability to break down a large piece of code into components
and functions. That concept is called modularity.

In Node.js, npm (Node Package Manager) is the default package manager for Node.js.
It gets installed into the system with the installation of Node.js. The required packages
and modules in the Node.js project are installed using NPM. Node.js is famous because
of NPM which is currently the world's largest collection of packages of code with more
than 1 million packages or modules. To install any module with npm, simply write the
following code in the terminal:

Importing npm Modules: Third-party modules are available online using the Node
Package Manager(NPM). These modules can be installed in the project folder or
globally (-g). You can go to the NPM official website and search for your required
module from 1 million packages.

Example 1: Let's search for a module called "superheroes" and create a simple
application:

First, go to the NPM website and search for superheroes. You can now install that
module by writing the following code in the terminal:

npm i superheroes

Note: 'i' is also permitted to install single modules.

index.js: Now, write the below code in the index.js file:

Javascript
var superheroes = require('superheroes');

var Name = superheroes.random();


console.log(Name);

Output:

In the above example, we are first importing the superheroes module by using
require() function. Then, we are printing the random hero names by calling the
random() method on the superheroes variable.

Example 2: Let's search for a module called "marvel-comics-characters" and create a


simple application:
First, go to the NPM website and search for marvel-comics-characters. You can now
install that module by writing the following code in the terminal:

npm i marvel-comics-characters

Javascript
var names = require('marvel-comics-characters');
var heroes = names.random(3);

var hero = [...heroes];


console.log(`${hero[0]} tried to kill ${hero[1]},
but ${hero[2]} saved him.`);

Output:

Some of the popular third-party modules are mongoose, express, angular, and react.
To install Third-party Modules, write the following command in the terminal:

npm install express


npm install mongoose
npm install -g @angular/cli

Basic Routes

Routing is one of the most significant parts of any website or web application.
Routing defines the way in which the client requests are handled by the application
endpoints. It is the mechanism by which requests (as specified by a URL and HTTP
method) are routed (directed) to the code that handles them.
The following are two methods for implementing routing in node.js:

 Using Framework
 Without using Framework

Using Framework: Node.js has many frameworks that help you to get your server
up and running. The most popular is Express.js. Express.js is a powerful framework for
node.js. One of the main advantages of this framework is defining different routes or
middleware to handle the client’s different incoming requests. In this article, we will
discuss, how to use the router in the express.js server.

Routing with Express: Express.js has an “app” object corresponding to HTTP. We


define the routes by using the methods of this “app” object. This app object specifies
a callback function, which is called when a request is received. We have different
methods in the app objects for different types of requests.

For GET request use app.get() method:

var express = require('express')


var app = express()

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


res.send('Welcome to GFG')
})
For POST request use app.post() method:

var express = require('express')


var app = express()

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


res.send('Welcome to GFG')
})

For handling all HTTP methods (i.e. GET, POST, PUT, DELETE etc.) use
app.all() method:

var express = require('express')


var app = express()

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


console.log('Welcome to GFG')
next() // Pass the control to the next handler
})

The next() is used to hand off the control to the next callback. Sometimes we use
app.use() to specify the middleware function as the callback.

So, to perform routing with the Express.js, you have only to load the express and then
use the app object to handle the callbacks according to the requirement.
Routing without Framework: Using the frameworks is good to save time, but
sometimes this may not suit the situation. So, a developer may need to build up their
own server without other dependencies.
Now create a file with any name using the .js extension and follow the steps to
perform routing from scratch:

Here we will use the built-in module of node.js i.e. HTTP. So, First load HTTP:

var http = require('http');

Now create the server by adding the following lines of code:

http.createServer(function (req, res) {


res.write('Hello World!'); // Write a response
res.end(); // End the response
}).listen(3000, function() {

// The server object listens on port 3000


console.log("server start at port 3000");
});

Now add the following lines of code in the above function to perform routing:

var url = req.url;


if(url ==='/about') {
res.write('Welcome to Courses');
res.end();
} else if(url ==='/contact') {
res.write('Welcome to Courses');
res.end();
} else {
res.write('GeeksforGeeks!');
res.end();
}

Example: The complete code of routing by combining the above code:

Javascript
var http = require('http');

// Create a server object


http.createServer(function (req, res) {

// http header
res.writeHead(200, {'Content-Type': 'text/html'});

var url = req.url;

if(url ==='/about') {
res.write('Welcome to Courses');
res.end();
}
else if(url ==='/contact') {
res.write('Welcome to Courses');
res.end();
}
else {
res.write('Hello World!');
res.end();
}
}).listen(3000, function() {

// The server object listens on port 3000


console.log("server start at port 3000");
});

Steps to run the server: Write the below code in the terminal to run the program:
node index.js

Output:

Creating a server

Node.js is an open-source and cross-platform runtime environment for executing


JavaScript code outside a browser. We often use Node.js for building back-end
services APIs like Web App or Mobile App. In this article, we will discuss how to make a
web server using node.js.

Creating Web Servers using Node.js: There are primarily two methods for
creating a web server using a node.js:

 Inbuilt module
 Third-party module

Inbuilt Module: There is an HTTP module that comes with the node itself. HTTP and
HTTPS, are these two inbuilt modules that give us networking capabilities that are
used to create a simple server. The HTTPS module provides the feature of the
encryption of communication with the help of the secure layer feature of this module.
Whereas the HTTP module doesn’t provide the encryption of the data.

To create a server, we must first require the HTTP module in the program, and then
start the server to listen for incoming requests.

const http = require('http');


First, we utilize the HTTP module's createServer() method, which accepts a callback
function that will be triggered whenever a new request arrives on our server. This
callback function also has access to two crucial core variables. It consists of two
variables ie: request and response.

const server = http.createServer((req, res) => {


res.end("Welcom to GeeksforGeeks")
});

Now, we actually need to listen to incoming requests from the client. On the built
server, the listen() method is used, which accepts a callback that handles the port on
which you want to run the server. Then, it takes an optional parameter where we can
assign the domain like localhost (127.0.0.1). And then, it takes a callback function.

server.listen(3000, function () {
console.log("Server is up on port 3000");
})

Our server is now ready to run. To run the server we need to write the below
command in the terminal:

node filename

Example: This is a simple program that will show you how to make a simple server
using an inbuilt module:

Javascript
const http = require('http');

const server = http.createServer((req, res) => {


res.end("Welcom to GeeksforGeeks")
});

server.listen(3000, function () {
console.log("Server is up on port 3000");
})

Start the application: Write the below command in the terminal to run the
application:

node index.js

Output:
Third-party module: Express.js is one of the most powerful frameworks of node.js
that works on the upper layer of the HTTP module. The main advantage of using the
express.js server is filtering the incoming requests by clients.

To use express in our application, we first need to install it as you know it's a third-
party module. To install express, write the below command in the terminal and hit
enter:

npm i express

After successful installation to use express in the program, we need to do the very
first and basic step which is to require the express module in the program and create
a variable called app and assign the result of calling express:

const express = require('express');


const app = express();

Now, we are ready to create and start up the server. We need to use listen() method
on the app variable to startup the server which again takes parameters as a port and
a callback function.

server.listen(3000, function () {
console.log("Server is up on port 3000");
});

All we need to do now is to define routes. Routing defines the way in which the client
requests are handled by the application endpoints. We can set up a route simply by
using the get() method on the app variable and passing the URL. We are specifying
the root ('/') URL here. And the second argument will be the callback function which
accepts the core variables req and res. We can use the res variable to send the data
to the client by using send() method.

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


res.send("GeeksforGeeks: A Computer Science portal for geeks.");
});

Example: This is a simple program that will show you how to make a simple server
using a third party module:

Javascript
const express = require('express');
const app = express();

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


res.status(200);
res.send("GeeksforGeeks: A Computer
Science portal for geeks.");
});

app.listen(3000, function () {
console.log("Server is up on port 3000");
});

Start the application: Write the below command in the terminal to run the
application:

node index.js

Output:

How to Run Synchronous Queries using sync-sql Module in Node.js ?

The sync-sql module is designed to make synchronous queries to the database. Since
normal SQL queries are asynchronous in node.js but if you want to run it
synchronously, then it is possible using this module. In synchronized SQL, the result
set is returned when the query is executed.

Note: Do not use this module in production mode as node.js is designed to be


asynchronous.

Installation of sync-sql module:

1. You can visit the link Install sync-sql module. You can install this package by
using this command.
2. npm install sync-sql

3. After installing sync-sql you can check your sync-sql version in command
prompt using the command.
4. npm version sync-sql

5. After that, you can just create a folder and add a file for example index.js, To
run this file you need to run the following command.
6. node index.js
7. Now open MySQL and create a database for example 'demo'.

Filename: index.js
javascript

const Mysql = require('sync-mysql')

const connection = new Mysql({


host:'localhost',
user:'root',
password:'password',
database:'demo'
})

var result = connection.query('SELECT NOW()')


console.log(result)
Steps to run the program:

1. The project structure will look like this:

2. Make sure you install sync-sql using following commands:


3. npm install sync-sql

4. Run index.js file using below command:


5. node index.js
So this is how you can run synchronized SQL queries in node js using sync-sql
package.
API Requests using HTTP Module

In the world of REST API, making an HTTP request is the core functionality of modern
technology. Many developers learn it when they land in a new environment. Various
open-source libraries including NodeJS built-in HTTP and HTTPS modules can be used
to make a network request from NodeJS.

Node.js provides two core modules for making HTTP requests. The HTTP module can
be used to make HTTP requests and the HTTP module can be used to make HTTPS
requests. One great feature of the request is that it provides a single module that can
make both HTTP and HTTPS requests.

Feature of HTTPS module:

1. It is easy to get started and easy to use.


2. It is a widely used and popular module for making https calls.

Here, we will send the request to https://jsonplaceholder.typicode.com/ API and show


the response’s data. Here are all the REST APIs.

REST
Method Detail
API
GET /posts Listing all resources

GET /posts/<id> Getting a resource

POST /posts Creating a resource

PUT /posts/<id> Updating a resource

Here we will send a request to get all resources using the HTTP module. NodeJS has a
built-in HTTP module to make a network request. But the drawback is that it is not
too user-friendly like the other solution. You, need to manually parse the data after
received.

Example: This is a basic example of Requesting API using HTTP Module:

Javascript
const http = require('http');

// Setting the configuration for


// the request
const options = {
hostname: 'jsonplaceholder.typicode.com',
path: '/posts',
method: 'GET'
};

// Sending the request


const req = http.request(options, (res) => {
let data = ''

res.on('data', (chunk) => {


data += chunk;
});

// Ending the response


res.on('end', () => {
console.log('Body:', JSON.parse(data))
});

}).on("error", (err) => {


console.log("Error: ", err)
}).end()

Start the application: Write the below command in the terminal to run the
application:

node index.js

Output:
Handling Errors

Node.js is a JavaScript extension used for server-side scripting. Error handling is a


mandatory step in application development. A Node.js developer may work with both
synchronous and asynchronous functions simultaneously. Handling errors in
asynchronous functions is important because their behavior may vary, unlike
synchronous functions. While try-catch blocks are effective for synchronous functions,
asynchronous functions can be deal with callbacks, promises, and async-await. Try-
catch is synchronous means that if an asynchronous function throws an error in a
synchronous try/catch block, no error throws. Operational errors and Programming
errors are two different sorts of errors that might occur.

Operational errors are issues that we may expect to occur at some point in the
future. So all we have to do now is deal with them ahead of time. They are unrelated
to any bugs in our code. They rely on the user, the system, or the network instead.
Things like a user accessing an invalid route path, invalid user input, and a bad
connection to a server are operational issues that we'll need to manage in order to
prepare our app for these scenarios.

Whereas, Programming errors are simply defects introduced into our code by us
developers, such as trying to read properties from an undefined variable, using await
without async, and so on.

Errors in Node.js applications can be handled in the following ways:

1. Using try-catch block


2. Using callbacks
3. Using promises and promise callbacks
4. Using async-await
Using try-catch block: The try-catch block can be used to handle errors thrown by a
block of code.

Javascript
function display() {
throw new Error(
'error is thrown from display');
}

function handleError() {
try {
display();
}
catch (e) {
console.log(e);
}
console.log(
"Keeping the program running");
}

handleError();

Output:
The handleError() function is called which in turn calls display() function which throws
an error object. This error object is caught by the catch block of the handleError()
method. If there is no proper handling of the error the program will terminate. The
catch block prints the call stack to show the point where the error occurred.

Using callbacks: A callback is a function called at the completion of a certain task.


Callbacks are widely used in Node.js as it prevents any blocking, and allow other code
to be run in the meantime. The program does not wait for file reading to complete and
proceeds to print “Program Ended” while continuing to read the file. If any error
occurs like a file does not exist in the system then the error is printed after “Program
Ended”, else the content of the file is outputted.

Javascript
var fs = require("fs");

fs.readFile('gfg.txt', function (err, data) {


if (err) {
console.error(err);
} else {
console.log(data.toString());
}
});

console.log("End of Code");

Output:

In this case, the file does not exist in the system hence the error is thrown.

Using promises and promise callbacks: Promises are an enhancement to Node.js


callbacks. When defining the callback, the value which is returned is called a
“promise”. The key difference between a promise and a callback is the return value.
There is no concept of a return value in callbacks. The return value provides more
control for defining the callback function. In order to use promises, the promise
module must be installed and imported into the application. The .then clause handles
the output of the promise. If an error occurs in any .then clause or if any of the
promises above rejects, it is passed to the immediate .catch clause. In case of a
promise is rejected, and there is no error handler then the program terminates.

Javascript
var Promise = require('promise');
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost/TestDB';

MongoClient.connect(url)
.then(function (err, db) {
db.collection('Test').updateOne({
"Name": "Joe"
}, {
$set: {
"Name": "Beck"
}
});
})
.catch(error => console.log(error.message));

Output:

Using async-await: Async-await is a special syntax to work with promises in a


simpler way that is easy to understand. When we use async/await, .then is replaced
by await which handles the waiting in the function. The error handling is done by
the .catch clause. Async-await can also be wrapped in a try-catch block for error
handling. In case no error handler exists the program terminates due to an uncaught
error.

Javascript
async function f() {
let response = await fetch('http://xyzurl');
}
// f() becomes a rejected promise
f().catch(alert);

Output:

Async and Await Node.js

Node.js architecture is single-threaded and asynchronous, the community devised the


callback functions, which would fire (or run) after the first function run is completed.
Before Node version 7.6, the callbacks were the only official way provided by Node to
run one function after another. There are different ways to handle the asynchronous
code in Node.js or in JavaScript which are:

 Callbacks
 Promises
 Async/Await

1. Callbacks: A callback is a function that is called when a task is completed, thus


helping in preventing any kind of blocking and a callback function allows other code to
run in the meantime. The callback is called when the task gets completed and is the
asynchronous equivalent to a function. Callbacks are an excellent approach to dealing
with something after it has been accomplished. By something here, we mean a
function execution. If we want to execute a function right after the return of some
other function, then callbacks can be used.
Callback hell is a big issue caused by coding with complex nested callbacks. Here,
each and every callback takes an argument that is a result of the previous callbacks.
In this manner, the code structure looks like a pyramid, making it difficult to read and
maintain. Also, if there is an error in one function, then all other functions get
affected.

2. Promises: A Promise in Node.js is similar to a promise in real life. It is an


assurance that something will be done. A promise is used to keep track of whether the
asynchronous event has been executed or not and determines what happens after the
event has occurred. It is an object having 3 states namely:

 Pending: Initial State, before the event has happened.


 Resolved: After the operation was completed successfully.
 Rejected: If the operation had an error during execution, the promise fails.

Error Handling of Promises: For a successfully resolved promise, we use .then()


method and for rejected promise, we use .catch() method. To run a code after the
promise has been handled using .then() or .catch() method, we can .finally() method.
The code inside .finally() method runs once regardless of the state of the promise.

Example:

Javascript
const promise = new Promise(function (resolve, reject) {
const string1 = "geeksforgeeks";
const string2 = "geeksforgeeks";
if (string1 === string2) {
resolve();
} else {
reject();
}
});

promise
.then(function () {
console.log("Promise resolved successfully");
})
.catch(function () {
console.log("Promise is rejected");
});

Output:

3. Async/Await: Async/Await is used to work with promises in asynchronous


functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle
code and make promises easier to read and use. It makes asynchronous code look
more like synchronous/procedural code, which is easier to understand.

Await can only be used in async functions. It is used for calling an async function and
waits for it to resolve or reject. Await blocks the execution of the code within the
async function in which it is located.
Error Handling in Async/Await: For a successfully resolved promise, we use try and
for rejected promise, we use catch. To run a code after the promise has been handled
using the try or catch, we can .finally() method. The code inside .finally() method runs
once regardless of the state of the promise.

Example:

Javascript
const helperPromise = function () {
const promise = new Promise(function (resolve, reject) {
const x = "geeksforgeeks";
const y = "geeksforgeeks";
if (x === y) {
resolve("Strings are same");
} else {
reject("Strings are not same");
}
});

return promise;
};

async function demoPromise() {


try {
let message = await helperPromise();
console.log(message);
} catch (error) {
console.log("Error: " + error);
}
}

demoPromise();
Output:

Hello Express

Express is a Node.js framework that is built on top of Node.js, providing a higher


degree of abstraction. In addition, it is the most widely used Node.js framework.
Complex routing, easier handling of requests and responses, adding middleware,
server-side rendering, and so on are just a few of the features included in Express. It
enables quick Node.js application development. It simplifies the integration of our
application into the MVC architecture.

Installation of Express: If you already have node.js installed on your PC, you may
install express on Windows by following these steps:

Step 1: Create a directory for our project and make that our working directory.

$ mkdir <foldername>
$ cd <foldername>

Step 2: Use the npm init command to create a package.json file for our project.
$ npm init

This command describes all the dependencies of our project. The file will be updated
when adding further dependencies during the development process, for example
when you set up your build system.

Step 3: Installing Express. Now in your project folder type the following command
line:

$ npm install express


Step 4: Check for express in the "dependencies" section of the package.json file to
see if it was successfully installed.

Serving HTML and JSON

Express is a Node.js framework that is built on top of Node.js, providing a higher


degree of abstraction. In addition, it is the most widely used Node.js framework.
Complex routing, easier handling of requests and responses, adding middleware,
server-side rendering, and so on are just a few of the features included in Express. It
enables quick Node.js application development. It simplifies the integration of our
application into the MVC architecture.
In express, we can access or display data from the server to the client directly on the
website as a rendered HTML. We can serve any data to the browser/front end using
nodeJS with the help of “express” and the in-built nodeJS file system “fs“. Here we
would use the HTML to view the data on the webpage. We would use express for
routing purposes.

Installation of the express module:

Step 1: Create the project folder, move into that folder and create an app.js file by
using the below command in the terminal:

mkdir gfg
cd gfg
touch app.js

Step 2: Configure the Node package.json file in the project folder:

npm init -y

Step 3: Install the express module:

npm install express

Project Structure: Your project structure should look like this:


Example 1: In the below example we are sending HTML data to the webpage from
the server-side rendering:

Javascript
const express = require('express');
const app = express();

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


res.write('<h1>Welcome to GeeksforGeeks</h1>');
res.write('
<p>A Computer Science portal for geeks.
It contains well written, well thought and well
explained computer science and programming
articles</p>
');
res.send();

});

app.listen(3000, function () {
console.log("Server is up at port 3000");
})

Output:
Example 2: In the below example we are simply printing the JSON data to the
webpage from the server-side rendering:

Javascript
const express = require('express');
const app = express();

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


res
.status(200)
.json({ message: `Welcome to GeeksforGeeks`,
website: `www.geeksforgeeks.org` });

});

app.listen(3000, function () {
console.log("Server is up at port 3000");
})

Output:
Dynamic Pages with Templating

Dynamic pages are a rendered webpage that is delivered to the client by the server
and contains all of the data that should be displayed on the website. To accomplish
so, we'll need to employ a template engine that allows us to generate a template and
then quickly fill it with data.

Template Engine: A template engine basically helps us to use static template files
with minimal code. At runtime, the template engine replaces all the variables with
actual values at the client-side.

Templating Engine Examples:

 EJS (Embedded JavaScript Templating)


 Pug
 Handlebars
 Mustache

In this article, we are going to use the Pug engine.


Setting up Pug: Follow the below steps to setup the project:

Step 1: Create the project folder, move into that folder and create an app.js file by
using the below command in the terminal:

mkdir gfg
cd gfg
touch app.js

Step 2: Configure the Node package.json file in the project folder:

npm init -y

Step 3: Install the express module:

npm install express

Step 4: Install pug:

npm i pug --save


Step 5: Now we need to add the below code in the Express app to tell it which
template engine we want to use, which we accomplish by adding the following code to
the app:

app.set('view engine', 'pub');

Step 6: Now we must specify the location of these views within our file system.

app.set('views', path.json(__dirname, 'view'));

Project Structure: This project should look like this:

Example: This is the basic example using pub to demonstrate Dynamic Pages with
Templating in express:

 app,js: This file contains the main server-side code of the application:

Javascript
const express = require('express');
const path = require('path');
const app = express();

app.set('views', path.join(__dirname, 'views'));


app.set('view engine', 'pug');

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


res.render('index');
});

app.listen(3000, function () {
console.log("Server started at port 3000");
})

 index.pug: This file contains the pub templates:

HTML
doctype html
html
head
title GeeksforGeeks
body
h1 GeeksforGeeks
p A Computer Science portal for geeks.

Output:
Example 2: This is the another example using pub to demonstrate Dynamic Pages
with Templating in express:

 app.js: This file contains the main server-side code of the application:

Javascript
const express = require('express');
const path = require('path');

const app = express();

app.set('views', path.join(__dirname, 'views'));


app.set('view engine', 'pug');

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


res.render('index', {
title: 'GeeksforGeeks',
data: 'A Computer Science portal for geeks.'
});
});

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


let templates = [
{
id: 1,
title: 'EJS'
},
{
id: 2,
title: 'Pug'
}, {
id: 3,
title: 'Handlebars'
},
{
id: 4,
title: 'Mustache'
},
];
res.render('add_template', {
title: 'Templates List',
templates: templates
});
})

app.listen(3000, function () {
console.log("Server started at port 3000");
})

 index.pug: This file contains the pub templates for /home route:

HTML
doctype html
html
head
title GeeksforGeeks
body
h1 #{title}
p #{data}

 template.pug: This file contains the pub templates for /template route:

HTML
doctype html
html
head
title GeeksforGeeks
body
h1 #{title}
ul
each template, i in templates
li= template.title

Output:
MongoDB and NoSQL Database

MongoDB the most popular NoSQL database is an open-source document-oriented


database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t
based on the table-like relational database structure but provides an altogether
different mechanism for the storage and retrieval of data. This format of storage is
called BSON (Similar to JSON format).

A simple MongoDB document Structure:

{
title: 'Geeksforgeeks',
by: 'Gaurav Jha',
url: 'https://www.geeksforgeeks.org',
type: 'NoSQL'
}
A NoSQL originally referring to non SQL or non-relational is a database that provides a
mechanism for storage and retrieval of data. This data is modeled in means other
than the tabular relations used in relational databases. A NoSQL database includes
simplicity of design, simpler horizontal scaling to clusters of machines, and finer
control over availability. The data structures used by NoSQL databases are different
from those used by default in relational databases which makes some operations
faster in NoSQL.

Features of MongoDB:

 Document Oriented: MongoDB stores the main subject in the minimal number
of documents and not by breaking it up into multiple relational structures like
RDBMS. For example, it stores all the information of a computer in a single
document called Computer and not in distinct relational structures like CPU,
RAM, Hard disk, etc.
 Indexing: Without indexing, a database would have to scan every document of
a collection to select those that match the query which would be inefficient. So,
for efficient searching Indexing is a must and MongoDB uses it to process huge
volumes of data in very less time.
 Scalability: MongoDB scales horizontally using sharding (partitioning data
across various servers). Data is partitioned into data chunks using the shard
key, and these data chunks are evenly distributed across shards that reside
across many physical servers. Also, new machines can be added to a running
database.
 Replication and High Availability: MongoDB increases the data availability
with multiple copies of data on different servers. By providing redundancy, it
protects the database from hardware failures. If one server goes down, the data
can be retrieved easily from other active servers which also had the data stored
on them.
 Aggregation: Aggregation operations process data records and return the
computed results. It is similar to the GROUPBY clause in SQL. A few aggregation
expressions are sum, avg, min, max, etc.

Where do we use MongoDB?

MongoDB is preferred over RDBMS in the following scenarios:


 Big Data: If you have a huge amount of data to be stored in tables, think of
MongoDB before RDBMS databases. MongoDB has a built-in solution for
partitioning and sharding your database.
 Unstable Schema: Adding a new column in RDBMS is hard whereas MongoDB
is schema-less. Adding a new field does not affect old documents and will be
very easy.
 Distributed data Since multiple copies of data are stored across different
servers, recovery of data is instant and safe even if there is a hardware failure.

Advantages of NoSQL: There are many advantages of working with NoSQL


databases such as MongoDB and Cassandra. The main advantages are high scalability
and high availability.

 High scalability: NoSQL databases use sharding for horizontal scaling.


Partitioning of data and placing it on multiple machines in such a way that the
order of the data is preserved is sharding. Vertical scaling means adding more
resources to the existing machine whereas horizontal scaling means adding
more machines to handle the data. Vertical scaling is not that easy to
implement but horizontal scaling is easy to implement. Examples of horizontal
scaling databases are MongoDB, Cassandra, etc. NoSQL can handle a huge
amount of data because of scalability, as the data grows NoSQL scale itself to
handle that data in an efficient manner.
 High availability: The auto replication feature in NoSQL databases makes it
highly available because in case of any failure data replicates itself to the
previous consistent state.

When should NoSQL be used:

1. When a huge amount of data needs to be stored and retrieved.


2. The relationship between the data you store is not that important
3. The data changes over time and is not structured.
4. Support of Constraints and Joins is not required at the database level
5. The data is growing continuously and you need to scale the database regularly
to handle the data.

Installing MongoDB
MongoDB the most popular NoSQL database is an open-source document-oriented
database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t
based on the table-like relational database structure but provides an altogether
different mechanism for the storage and retrieval of data. This format of storage is
called BSON (Similar to JSON format).

Installing MongoDB on your Windows:

Step 1: To download the MongoDB, go to the official MongoDB website and click
Download.

Here, You can select any version, Windows, and package according to your
requirement. For Windows, we need to choose:

 Version: 4.2.2
 OS: WindowsOS
 Package: MSI

Step 2: When the download is complete open the MSI file and click the next
button on the startup screen:

Step 3: Now accept the End-User License Agreement and click the next button:
Step 4: Now select the complete option to install all the program features. Here, if
you can want to install only selected program features and want to select the location
of the installation, then use the Custom option:
Step 5: Select “Run service as Network Service user” and copy the path of the data
directory. Click Next:
Step 6: Click the Install button to start the installation process:

Step 7: After clicking on the install button installation of MongoDB begins:


Step 8: Now click the Finish button to complete the installation process:
Step 9: Now we go to the location where MongoDB was installed in step 5 in your
system and copy the bin path:

Step 10: Now, to create an environment variable open system properties <<
Environment Variable << System variable << path << Edit Environment variable and
paste the copied link to your environment system and click Ok:
Step 11: After setting the environment variable we will run the MongoDB server, i.e.
mongod. So, open the command prompt and run the following command:

mongod

When you run this command you will get an error i.e. C:/data/db/ not found.

Step 12: Now, Open the C drive and create a folder named “data” inside this folder
create another folder named “db”. After creating these folders. Again open the
command prompt and run the following command:

mongod
Now, this time the MongoDB server(i.e., mongod) will run successfully.

Run mongo Shell: The mongo shell is a JavaScript-based interactive MongoDB


interface. The mongo shell can be used to query and update data, as well as to
conduct administrative tasks.

Step 13: Now we are going to connect our server (mongod) with the mongo shell. So,
keep that mongod window and open a new command prompt window and
write mongo. Now, our mongo shell will successfully connect to the mongod.
Note: Please do not close the mongod window if you close this window your server
will stop working and it will not able to connect with the mongo shell.

Now, you are ready to write queries in the mongo Shell.

Example: Now you can make a new database, collections, and documents in your
shell. Below is an example of how to make a new database:

The use Database_name commend makes a new database in the system if it does not
exist, if the database exists it uses that database:
use gfg

Now your database is ready for name gfg.

The db.Collection_name commend makes a new collection in the gfg database and
the insertOne() method inserts the document in the student collection:

db.student.insertOne({Akshay:500})

Connect with DB and Queries

MongoDB, the most popular NoSQL database is an open-source document-oriented


database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t
based on the table-like relational database structure but provides an altogether
different mechanism for storing and retrieving data. This format of storage is called
BSON ( similar to JSON format).

There are essentially two alternatives when constructing a Node application that has
to connect to a MongoDB database:
 Use the native MongoDB driver
 Using Mongoose

Use the native MongoDB driver: First, see how we can connect your Node
application to the MongoDB database using the native driver. We need to install the
MongoDB package through the npm manager and then require it into our application
to establish a connection.

Setting up Application: Follow the below steps to set up the project structure:

Step 1: Create your project directory and move to the directory:

mkdir carDB
cd carDB

Spet 2: Initialize the Node npm init and yes to all the options:

npm init -y

Step 3: Install the MongoDB driver dependency:

npm install --save mongodb


Project Structure: Your Project Should look like this:

Example: The below code is establishing a connection to the MongoDB server and
inserting documents using the native driver:

Javascript
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'carDB';

// Create a new MongoClient


const client = new MongoClient(url);

// Use connect method to connect to the server


client.connect(function (err) {
assert.equal(null, err);
console.log("The server was successfully connected.");

const db = client.db(dbName);

insertDocuments(db, function () {
client.close();
});
});
const insertDocuments = function (db, callback) {

// Get the documents collection


const collection = db.collection('cars');

// Insert some docuents


collection.insertMany([
{
name: "Grand i10 Nios",
color: "Aqua Teal",
cc: 1145
},
{
name: "Swift Desire",
color: "moon white",
cc: 1087
}, {
name: "Creta",
color: "Shine Black",
cc: 1480
}
], function (err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("3 documents were added to the collection.");
callback(result);
});
}

Steps to run the application: Write the below code in the terminal to run the
application

node app.js
Output:

The database will be updated in the following manner:

Using Mongoose: Mongoose is an Object Data Modeling (ODM) library for MongoDB.
It allows your Node.js application, which understands JavaScript objects to
communicate with your MongoDB database, which understands docs, collections, and
databases. And practically everything we accomplished previously with the MongoDB
driver can be done with Mongoose by simply writing:

Javascript
const mongoose = require('mongoose');

mongoose.connect("mongodb://localhost:27017/databaseName");
const dbs = mongoose.model("dbs", {name: String});

const item = new dbs({name: "item 1"});

item.save();

Installation: In the above project folder, install the mongoose package using npm:

npm install mongoose

and require the mongoose in the project using the below line at the top of the code:

const mongoose = require("mongoose");

Example: The below code is establishing a connection to the MongoDB server and
inserting documents using mongoose:

Javascript
const mongoose = require('mongoose');

// Connecting to the Database at port 27017


mongoose.connect("mongodb://localhost:27017/carDB");

// Create New Schema called carSchema


const carSchema = new mongoose.Schema({
name: String,
color: String,
cc: Number
});

// Create New Collection called Cars


const Cars = mongoose.model("Cars", carSchema);
// Inserting Data
const Nios = new Cars({
name: "Grand i10 Nios",
color: "Aqua Teal",
cc: 1145
});

const Swift = new Cars({


name: "Swift Desire",
color: "moon white",
cc: 1087
});

const Creta = new Cars({


name: "Creta",
color: "Shine Black",
cc: 1480
});

// Saving Data to Database


Cars.insertMany([Nios, Swift, Creta], function (err) {
if (err) {
console.log(err);
} else {
console.log("All of the cars were successfully saved to carDB.");
}
});

Steps to run the setup: Write the below code in the terminal and then check your
database, it should update the database with a new collection:

node app.js

Output:
Setting up Mongoose & Create Mongoose Model

Mongoose is an Object Data Modeling (ODM) library for MongoDB. It defines a


strongly-typed-schema with default values and schema validations which are later
mapped to a MongoDB document. It allows your Node.js application which
understands JavaScript objects, to communicate with your MongoDB database, which
understands docs, collections, and databases.

For creating a collection with Mongoose, you have to create two necessary things:

1. Schema: It is a document structure that contains the property with its types
( default value, validations, etc. when required ) as a key-value pair.
2. Model: It is a class created with the help of a defined Schema and a MongoDB
document is an instance of the Model. Therefore, it acts as an interface for the
MongoDB database for creating, reading, updating, and deleting a document.

Install Mongoose:

Step 1: You can visit the link Install mongoose to install the mongoose module. You
can install this package by using this command.

npm install mongoose

Step 2: Now you can import the mongoose module in your file using:

const mongoose = require('mongoose');

Implementation:

Step 1: Create a folder and add model.js and index.js files to it.

 model.js: It contains schemas and models for all the collections you want to
create, and then we are exporting all the models created so that they can be
imported into the file in which we will create our collections.
 main.js: It is the main server file where we have inserted data into a collection.

Step 2: Write down the following code in the model.js file.

Javascript
// Requiring module
const mongoose = require('mongoose');

// Create New Schema called carSchema


const carSchema = new mongoose.Schema({
name: String,
color: String,
cc: Number
});

// Create New Collection called Cars


const Cars = mongoose.model("Cars", carSchema);

// Exporting our model objects


module.exports = Cars;

Step 3: Database connection can be easily established using mongoose like:

mongoose.connect("mongodb://localhost:27017/carDB");

If the database carDB is already present, the connection will be established otherwise
the first database will be created and a connection will be established. Here initially
we have an empty database carDB as shown in the image below:
Create data objects, you want to insert, for all the collections then insert them as
shown in the index.js file. As soon as we will insert data our collections will
automatically be created.

Step 4: Write down the following code in the index.js file.

Javascript
const mongoose = require('mongoose');
const Cars = require('./model.js');

// Connecting to the Database at port 27017


mongoose.connect("mongodb://localhost:27017/carDB");

// Inserting Data
const Nios = new Cars({
name: "Grand i10 Nios",
color: "Aqua Teal",
cc: 1145
});

const Swift = new Cars({


name: "Swift Desire",
color: "moon white",
cc: 1087
});

const Creta = new Cars({


name: "Creta",
color: "Shine Black",
cc: 1480
});

// Saving Data to Database


Cars.insertMany([Nios, Swift, Creta], function (err) {
if (err) {
console.log(err);
} else {
console.log("All of the cars were successfully saved to carDB.");
}
});

Steps to Run the Application: Write the below code in the terminal to run the
application:

node index.js

Output:

Structure REST API

API is an abbreviation for Application Programming Interface which is a collection of


communication protocols and subroutines used by various programs to communicate
between them.

REpresentational State Transfer (REST) is an architectural style that defines a set of


constraints to be used for creating web services. REST API is a way of accessing web
services in a simple and flexible way without having any processing. We only need to
follow a few rules to create RESTful APIs, which are APIs that follow the REST
Architecture:

1. Our API must be divided into logical resources.


2. These resources are needed to be exposed, which means they should be
accessible via URLs that are organized and resource-based.
3. The API should employ the appropriate HTTP methods to conduct various
actions on data, such as reading, generating, and removing data.
4. The JSON data format should be used for anything that we transmit back to the
client or receive from the client.
5. Stateless RESTful APIs are required.

Working:

A request is sent from client to server in the form of a web URL as HTTP GET or POST
or PUT or DELETE request. After that, a response comes back from the server in the
form of a resource which can be anything like HTML, XML, Image, or JSON. But now
JSON is the most popular format being used in Web Services.

In HTTP there are five methods that are commonly used in a REST-based Architecture
i.e., POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update,
and delete (or CRUD) operations respectively. There are other methods that are less
frequently used like OPTIONS and HEAD.

1. GET: The HTTP GET method is used to read (or retrieve) a representation of a
resource. In the safe path, GET returns a representation in XML or JSON and an HTTP
response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND)
or 400 (BAD REQUEST).
app.get("/cars", function(req, res){
Car.find(function(err, foundCars){
console.log(foundCars);
});
});

2. POST: The POST verb is most often utilized to create new resources. In particular,
it’s used to create subordinate resources. That is subordinate to some other (e.g.
parent) resource. On successful creation, return HTTP status 201, returning a Location
header with a link to the newly-created resource with the 201 HTTP status.
NOTE: POST is neither safe nor idempotent.

app.post("/cars", function(req, res){


const newCar = new Cars({
name: req.body.name,
color: req.body.color,
cc: req.body.cc,
});

newCar.save();
});

3. PUT: It is used for updating the capabilities. However, PUT can also be used
to create a resource in the case where the resource ID is chosen by the client instead
of by the server. In other words, if the PUT is to a URI that contains the value of a non-
existent resource ID. On successful update, return 200 (or 204 if not returning any
content in the body) from a PUT. If using PUT for creating, return HTTP status 201 on
successful creation. PUT is not a safe operation but it’s idempotent.

app.put(function (req, res) {


Cars.update(
{ name: req.params.carName },
{ color: req.params.carColor },
{ cc: req.params.carCC },
function (err) {
if (!err) {
res.send("Successfully updated car details");
} else {
res.send(err);
}
}
);
});

4. PATCH: It is used to modify capabilities. The PATCH request only needs to contain
the changes to the resource, not the complete resource. This resembles PUT, but the
body contains a set of instructions describing how a resource currently residing on the
server should be modified to produce a new version. This means that the PATCH body
should not just be a modified part of the resource but in some kind of patch languages
like JSON Patch or XML Patch. PATCH is neither safe nor idempotent.

app.patch(function (req, res) {


Cars.update(
{ name: req.params.carName },
{ color: req.params.carColor },
{ cc: req.params.carCC },
function (err) {
if (!err) {
res.send("Successfully updated car details");
} else {
res.send(err);
}
}
);
});

5. DELETE: It is used to delete a resource identified by a URI. On successful deletion,


return HTTP status 200 (OK) along with a response body.
app.delete('/cars', function (req, res) {
Cars.deleteMany(function (err) {
if (!err) {
res.send("Successfully deleted all cars.");
} else {
res.send(err);
}
});
});

HTTP
/cars /cars/Hyundai
Verbs

GET Fetches all the cars Fetches the cars of Hyundai

POST Creates one new car -

PUT - Updates the car details on Hyundai

PATCH - Updates the car details on Hyundai

DELETE Deletes all the cars Deletes the cars of Hyundai

Create EndPoints

API is an abbreviation for Application Programming Interface which is a collection of


communication protocols and subroutines used by various programs to communicate
between them.
A request is sent from client to server in the form of a web URL as HTTP GET or POST
or PUT or DELETE request. After that, a response comes back from the server in the
form of a resource which can be anything like HTML, XML, Image, or JSON. But now
JSON is the most popular format being used in Web Services.

We frequently need to know about endpoints, pathways, parameters, and


authentication while discussing APIs. These are the four essential components of an
API.

Endpoint: There will be an endpoint for any API that interacts with an external
system, such as a server. We can utilize their API to obtain data from other
applications to use on our own, and the endpoint of any API is the first portion of the
URL. If we want to include a weather forecast function in our app, we'll need to have
access to the weather service provider's API and connect it with our app. For
instance, openweathermap.org includes all weather-related information. As a result,
their API's endpoint should be:

https://api.openweathermap.org/data/2.5/weather

Paths and Parameters: You can utilize API paths and parameters to narrow down on
a specific piece of data from an external service. After the endpoint, we must define a
specific path and parameter that will return data for that parameter. APIs normally
allow you to provide parameters in order for them to be flexible enough to deal with
custom queries. And parameters appear at the end of the URL, following a question
mark (? ), and are followed by a key-value pair. For example, if we want to know what
the current temperature is in a specific region. In such instance, after the endpoint in
the API that provides the requested information, we must specify the latitude and
longitude, as seen below:
https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}

Authentication: When it comes to data that is more monetizable or that allows


developers to construct more complex applications that may be utilized by thousands
of people, these websites must start thinking very hard about how to either monetize
or limit your usage of their data. And the way they'd accomplish it would be through
authentication. So they have to be able to identify you as the developer every time
you make an API request, and they have to keep track of how often you use their
server to collect data, and then charge you or limit you accordingly. For example, to
use openweathermap.org's API, we must supply our permitted API key-id, which must
be provided together with the URL:

https://api.openweathermap.org/data/2.5/weather?
lat={lat}&lon={lon}&appid={API key}

Create your own API EndPoints: Let's look at how we can develop our own API
with endpoints and share our data and resources with other applications as an
external system or server:

Setting up project: Setup the project to create your own RESTful API with EndPoints:

Step 1: Create the project folder, move into that folder and create an app.js file by
using the below command in the terminal:

mkdir gfg
cd gfg
touch app.js
Step 2: Configure the Node package.json file in the project folder:

npm init -y

Step 3: Install all the required modules:

npm i express ejs mongoose body-parser

Project Structure: This project should look like this:

Example: This is the basic example that will demonstrate the creation of API
EndPoints:

Javascript
// Requiring all the modules
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require('mongoose');

const app = express();

app.set('view engine', 'ejs');


app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));

// Connecting mongoDB database


mongoose.connect("mongodb://localhost:27017/carDB");

// Creating Schema
const carSchema = {
name: String,
color: String,
cc: Number
};

// Creating collection
const Cars = mongoose.model("Cars", carSchema);

// Setting up routes
app.route("/cars")

.get(function (req, res) {


Cars.find(function (err, cars) {
if (cars) {
const jsonCars = JSON.stringify(cars);
res.send(jsonCars);
} else {
res.send("No cars currently in wikiDB.");
}
});
})

.post(function (req, res) {


const newCar = Car({
name: req.body.name,
color: req.body.color,
cc: req.body.cc,
});

newCar.save(function (err) {
if (!err) {
res.send("Successfully added a new car.");
} else {
res.send(err);
}
});
})

.delete(function (req, res) {

Cars.deleteMany(function (err) {
if (!err) {
res.send("Successfully deleted all the cars in carDB.");
} else {
res.send(err);
}
});
});

// Running up the server


app.listen(3000, function () {
console.log("Server started on port 3000");
});

Steps to run the application: run the following command in the terminal to run the
server up:

node app.js

Output:
CRUD Operations

Mongoose is basically a package that serves as a mediator between the Node.js


application and MongoDB server. It is an Object Document Mapper (ODM) that allows
us to define objects with a strongly-typed-schema that is mapped to a MongoDB
document. Mongoose supports all the CRUD operations – Creating, Retrieving,
Updating, and Deleting.

Prerequisites: We will be using Express to set up our basic server, We would


recommend going through some articles on express and official express documents.
Other requirements include MongoDB Atlas and Postman.

Installation: Install the mongoose and the express module through npm using the
below command:
npm install express mongoose --save

CRUD Operations: The abbreviation CRUD expands to Create, Read,


Update and Delete. These four are fundamental operations in a database.

1. Create Operations: The create or insert operations are used to insert or add new
documents to the collection. If a collection does not exist, then it will create a new
collection in the database. You can perform, and create operations using the following
methods provided by the MongoDB:

 db.collection.insertOne(): It is used to insert a single document into the


collection.
 db.collection.insertMany(): It is used to insert multiple documents into the
collection.

Example 1: In this example, we are inserting details of a single car in form of a


document in the cars collection using db.collection.insertOne() method.

db.cars.insertOne({
name: "Polo",
color: "moonlight",
cc: 1234
})
Example 2: In this example, we are inserting details of multiple cars in form of a
document in the cars collection using db.collection.insertOne() method.

db.cars.insertMany([
{name: "baleno", color: "ocean blue", cc: 1107},
{name: "honda city", color: "matty grey", cc: 1370}
])

2. Read Operations: The Read operations are used to retrieve documents from the
collection, or in other words, read operations are used to query a collection for a
document. You can perform a read operation using the following method provided by
the MongoDB:

 db.collection.find(): It is used to retrieve documents from the collection.

Example: In this example, we are retrieving the details of cars from the cars
collection using db.collection.find() method.
db.cars.find()

3. Update Operations: The update operations are used to update or modify the
existing document in the collection. You can perform update operations using the
following methods provided by the MongoDB:

 db.collection.updateOne(): It is used to update a single document in the


collection that satisfies the given criteria.
 db.collection.updateMany(): It is used to update multiple documents in the
collection that satisfy the given criteria.
 db.collection.replaceOne(): It is used to replace a single document in the
collection that satisfies the given criteria.

Example: In this example, we are updating the color of Polo in the cars collection
using the db.collection.updateOne() method.

db.cars.updateOne(
{name: "Polo"},
{$set:{color: "Fossil White"}}
)
4. Delete Operations: The delete operation is used to delete or remove the
documents from the collection. You can perform delete operations using the following
methods provided by the MongoDB:

 db.collection.deleteOne(): It is used to delete a single document from the


collection that satisfies the given criteria.
 db.collection.deleteMany(): It is used to delete multiple documents from the
collection that satisfy the given criteria.

Example: In this example, we are deleting a polo car from the cars collection using
db.collection.deleteOne() method.

db.cars.deleteOne({name: "Polo"})

Securely storing Password

Authentication and authorization refer to the process of a user signing up for and
login into our app, as well as granting them access to areas of the app that are only
accessible to logged-in users. Most web applications require their users to
authenticate themselves by asking them to username and password. They compare
the user-supplied credentials with the data stored in their database and if the
credentials match, the user is granted access.
We'll need to establish a user database in order to create a user account and keep
their username and password. However, if we save the user's password in the
database as a string, it would be clearly visible, which is a security concern. If the
website is storing your password in plain text then no matter how strong the
password you choose, you are not safe!

To avoid that issue, we'll store the password in form of encryption instead of plain
text. Encryption is an encoding technique in which a message is encoded by using
an encryption algorithm in such a way that only authorized personnel can access the
message or information.

One of the famous methods of encrypting messages is the Caesar Cipher, which we
are also going to use in this article. The Caesar Cipher technique is one of the
earliest and simplest methods of encryption technique. It’s simply a type of
substitution cipher, i.e. each letter of a given text is replaced by a letter with a fixed
number of positions down the alphabet. For example with a shift of 1, A would be
replaced by B, B would become C, and so on. The method is apparently named after
Julius Caesar, who apparently used it to communicate with his officials.

Setting up project: Setup the project to create an application that stores the
password securely in the database:

Step 1: Create the project folder, move into that folder and create an app.js file by
using the below command in the terminal:

mkdir gfg
cd gfg
touch app.js

Step 2: Create a views folder in the gfg folder, and make four ejs files as home.ejs,
signup.ejs, login.ejs, and access.ejs:

mkdir views
cd views
touch home.ejs signup.ejs login.ejs access.ejs

Step 3: Configure the Node package.json file in the project folder:

npm init -y

Step 4: Install all the required modules:

npm i express body-parser ejs mongoose mongoose-encryption

Project Structure: This project should look like this:


Example: This example illustrates how to store passwords securely in the MongoDB
database:

home.ejs
<div>
<h1>GeeksforGeeks</h1>
<a href="/signup" role="button">Signup</a>
<a href="/login" role="button">Login</a>
</div>

signup.ejs
<div>
<h1>Signup</h1>
<form action="/signup" method="POST">
<label for="email">Email</label>
<input type="email" name="username">
<label for="password">Password</label>
<input type="password" name="password">
<button type="submit">Signup</button>
</form>
</div>

login.ejs
<div>
<h1>Login</h1>

<form action="/login" method="POST">


<label for="email">Email</label>
<input type="email" name="username">
<label for="password">Password</label>
<input type="password" name="password">
<button type="submit">Login</button>
</form>
</div>

access.ejs
<div class="jumbotron text-center">
<h1>GFG DASHBOARD</h1>
<p>You've Successfully logged into GFG dashboard!</p>
</div>

app.js
// Requiring modules
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const encrypt = require("mongoose-encryption");

const app = express();

app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));

// Connecting mongoDB
mongoose.connect("mongodb://localhost:27017/userDB");

// Creating userSchema
const userSchema = new mongoose.Schema({
email: String,
password: String
});

// Encrypting password field


const key = "GeeksforGeeks";
userSchema.plugin(encrypt, {
secret: key,
encryptedFields: ["password"]
});

// Creating Collection in mongoDB database


const User = new mongoose.model("User", userSchema);

// Routing the pages:

// GET requests
app.get('/', function (req, res) {
res.render("home");
});

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


res.render("login");
});

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


res.render("signup");
});

// Post requests
app.post('/signup', function (req, res) {
const newUser = new User({
email: req.body.username,
password: req.body.password
});

newUser.save(function (err) {
if (!err) {
res.render("access");
} else {
console.log(err);
}
});
});

app.post("/login", function (req, res) {


const username = req.body.username;
const password = req.body.password;

User.findOne({ email: username },


function (err, foundUser) {
if (err) {
console.log(err);
} else {
if (foundUser) {
if (foundUser.password === password) {
res.render("access");
}
}
}
});
});

// Stating up the server


app.listen(3000, function () {
console.log("Server is up at port 3000");
});

Steps to start the application: Write the below code in the terminal to run the
server up:

node app.js

Output:
Hashing Password with BcryptJS

Hashing is the process of converting the information into a key using a hash function.
The original information cannot be retrieved from the hash key by any means.
Generally, the hash keys are stored in the database and they are compared to check
whether the original information matches or not. They are generally used to store the
passwords for login. Some of the examples of a hashing algorithm are MD5 and
SHA256.

Hashing is mainly used for authentication purposes. Salting makes password hashing
more secure. Salting is an extra action during hashing. If two clients have the same
password, they will also have the same password hashes. A salt, which is a random
series of characters, is an extra input to the password before hashing. This makes an
alternate hash result for the two passwords. Salting makes it difficult to use lookup
tables and rainbow tables to crack a hash. A lookup table is a data structure that
processes several hash lookups every second.

Implementation of Salting: The following suggestions are used to implement


salting:
 The size of the salt should match the size of the hash function’s output.
 Always hash on the server in a web application.
 The salt should be unique for every user’s password.

While submitting the form, there are some sensitive data (like passwords) that must
not be visible to anyone, not even to the database admin. To avoid sensitive data
being visible to anyone, we can use an npm library known as bcryptjs.

This module enables storing of passwords as hashed passwords instead of plaintext.

Setting up project: Setup the project to create an application that does the hashing
password with BcryptJS:

Step 1: Create a project folder, move into that folder and create a file app.js by using
the below command in the terminal:

mkdir gfg
cd gfg
touch app.js

Step 2: Create a views folder in the gfg folder, and make four ejs files as home.ejs,
signup.ejs, login.ejs, and access.ejs:

mkdir views
cd views
touch home.ejs signup.ejs login.ejs access.ejs
Step 3: Configure the Node package.json file in the project folder:

npm init -y

Step 4: Install all the required modules:

npm i express body-parser ejs mongoose bcrypt

Project Structure: This project should look like this:

Example: This example illustrates how to store hashing password with BcryptJS in the
MongoDB database:

home.ejs
<div>
<h1>GeeksforGeeks</h1>
<a href="/signup" role="button">Signup</a>
<a href="/login" role="button">Login</a>
</div>

signup.ejs
<div>
<h1>Signup</h1>
<form action="/signup" method="POST">
<label for="email">Email</label>
<input type="email" name="username">
<label for="password">Password</label>
<input type="password" name="password">
<button type="submit">Signup</button>
</form>
</div>

login.ejs
<div>
<h1>Login</h1>

<form action="/login" method="POST">


<label for="email">Email</label>
<input type="email" name="username">
<label for="password">Password</label>
<input type="password" name="password">
<button type="submit">Login</button>
</form>
</div>

access.ejs
<div class="jumbotron text-center">
<h1>GFG DASHBOARD</h1>
<p>You've Successfully logged into GFG dashboard!</p>
</div>

app.js
// Requiring modules
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const bcrypt = require('bcrypt');

// No of Salting Rounds
const saltRound = 10;

const app = express();

app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));

// Connecting mongoDB
mongoose.connect("mongodb://localhost:27017/userDB");

// Creating userSchema
const userSchema = new mongoose.Schema({
email: String,
password: String
});

// Creating Collection in mongoDB database


const User = new mongoose.model("User", userSchema);

// Routing the pages:

// GET requests
app.get('/', function (req, res) {
res.render("home");
});

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


res.render("login");
});

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


res.render("signup");
});
// Post requests
app.post('/signup', function (req, res) {

// Applying Hashing
bcrypt.hash(req.body.password, saltRound, function (err, hash) {
const newUser = new User({
email: req.body.username,
password: hash
});

newUser.save(function (err) {
if (!err) {
res.render("access");
} else {
console.log(err);
}
});
});
});

app.post("/login", function (req, res) {


const username = req.body.username;
const password = req.body.password;

User.findOne({ email: username }, function (err, foundUser) {


if (err) {
console.log(err);
} else {
if (foundUser) {
// Comaring Hashing password in database
bcrypt.compare(password,
foundUser.password,
function (err, result) {
if (result === true) {
res.render("access");
}
});
}
}
});
});
// Stating up the server
app.listen(3000, function () {
console.log("Server is up at port 3000");
});

Steps to start the application: Write the below code in the terminal to run the
server up:

node app.js

Output:

User Logging

JSON Web Token or JWT is an open standard for securely transferring data within
parties using a JSON object. JWT is used for stateless authentication mechanisms for
users and providers. This means maintaining sessions on the client-side instead of
storing sessions on the server. Here, we will implement the JWT authentication system
in NodeJs.
If we already have a registered user in our database, the user's client will make a post
request using the username or email address and password. The program then
verifies that the user exists and that the password is correct. If that's the case, a
secret string saved on the server is used to construct a unique JSON Web Token for
that user. The server then sends the JWT to the client, which can save in a cookie or in
local storage. Without leaving any state on the server, the user is authorized and
effectively logged into our application. As a result, the server has no idea who is truly
logged in. However, because he has a valid JSON Web Token, the user is aware that
he is logged in.

The user then submits JSON Web Token along with a request each time then the user
wishes to access a protected route. After the request reaches the server, our app
checks to see if the JSON Web Token is genuine. If the request for data is valid, it will
be sent to the client. If it's invalid, the user will receive an error message stating that
he is not permitted to access that resource.

Setting up project: Setup the project to create an application for user Logging:

Step 1: Create the project folder, move into that folder and create an app.js file by
using the below command in the terminal:
mkdir gfg
cd gfg
touch app.js

Step 2: Configure the Node package.json file in the project folder:

npm init -y

Step 3: Install all the required modules:

npm i express jsonwebtoken

Project Structure: This project should look like this:

Example: This example illustrates the creation of user Logging with JWT:

Javascript
// Requiring modules
const express = require("express");
const jwt = require('jsonwebtoken');

const app = express();


const secretKey = 'geeksforgeeks';

// Get routes
app.get('/gfg', function (req, res) {
res.json({
message: "Welcome to geeksforgeeks"
});
});

// Post routes
app.post('/gfg/article', authToken, function (req, res) {
jwt.verify(req.token, secretKey, function (err, authData) {
if (err) {
res.sendStatus(403);
} else {
res.json({
message: 'Article Created',
authData
});
}
});
});

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


// Test User
const user = {
id: 1,
username: 'gaurav',
email: '[email protected]'
}

jwt.sign({ user: user }, secretKey, function (err, token) {


res.json({
token: token
});
});
});

// Authenticate Token
function authToken(req, res, next) {
// Get auth header value
const bearerHeader = req.headers['authorization'];
// Check if bearer is undefined
if (typeof bearerHeader !== 'undefined') {
// Split at the space
const bearer = bearerHeader.split(' ');

// Get token from array


const bearerToken = bearer[1];

// Set the token


req.token = bearerToken;

// Next middleware
next();
} else {
// Forbidden
res.sendStatus(403);
}
}

// Running up Server
app.listen(3000, function () {
console.log("Server is up at port 3000");
});

Steps to start the application: Write the below code in the terminal to run the
server up:

node app.js

Output:
JSON web tokens

A JSON web token(JWT) is JSON Object which is used to securely transfer information
over the web (between two parties). It can be used for an authentication system and
can also be used for information exchange. The token is mainly composed of
a header, payload, and signature. These three parts are separated by dots(.). JWT
defines the structure of information we are sending from one party to another, and it
comes in two forms – Serialized, and Deserialized. The Serialized approach is
mainly used to transfer the data through the network with each request and response.
While the deserialized approach is used to read and write data to the web token.

Deserialized: JWT in the deserialized form contains only the header and the payload.
Both of them are plain JSON objects.
Header: A header in a JWT is mostly used to describe the cryptographic operations
applied to the JWT like the signing/decryption technique used on it. It can also contain
the data about the media/content type of the information we are sending. This
information is present as a JSON object then this JSON object is encoded to
BASE64URL. The cryptographic operations in the header define whether the JWT is
signed/unsigned or encrypted and so then what algorithm techniques to use. A simple
header of a JWT looks like the code below:

{
"typ":"JWT",
"alg":"HS256"
}

The ‘alg’ and ‘typ’ are object key’s having different values and different functions like
the ‘typ’ gives us the type of the header this information packet is, whereas the ‘alg’
tells us about the encryption algorithm used.

Note: HS256 and RS256 are the two main algorithms we make use of in the header
section of a JWT.
Some JWT’s can also be created without a signature or encryption. Such a token is
referred to as unsecured and its header should have the value of the alg object key
assigned to as ‘none’.

{
"alg":"none"
}

Payload: The payload is the part of the JWT where all the user data is actually added.
This data is also referred to as the ‘claims’ of the JWT. This information is readable by
anyone so it is always advised to not put any confidential information in here. This
part generally contains user information. This information is present as a JSON object
then this JSON object is encoded to BASE64URL. We can put as many claims as we
want inside a payload, though, unlike the header, no claims are mandatory in a
payload. The JWT with the payload will look something like this:

{
"userId":"b07f85be-45da",
"iss": "https://provider.domain.com/",
"sub": "auth/some-hash-here",
"exp": 153452683
}

The above JWT contains userId, iss, sub, and exp. All these play a different role as
userId is the ID of the user we are storing, ‘iss’ tells us about the issuer, ‘sub’ stands
for the subject, and ‘exp’ stands for expiration date.

Serialized: JWT in the serialized form represents a string of the following format:

[header].[payload].[signature]

all these three components make up the serialized JWT. We already know what header
and payload are and what they are used for. Let’s talk about the signature.

Signature: This is the third part of JWT and is used to verify the authenticity of the
token. BASE64URL encoded header and payload are joined together with a dot(.) and
it is then hashed using the hashing algorithm defined in a header with a secret key.
This signature is then appended to the header and payload using dot(.) which forms
our actual token header.payload.signature
Syntax:

HASHINGALGO( base64UrlEncode(header) + “.” +


base64UrlEncode(payload),secret)

So all these above components together are what make up a JWT. Now let’s see what
our actual token will look like:

JWT Example:

header:

{
"alg" : "HS256",
"typ" : "JWT"
}

Payload:

{
"id" : 123456789,
"name" : "Joseph"
}

Secret: GeeksForGeeks
JSON Web Token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoxLCJ1c2VybmFtZSI6I
mdhdXJhdiIsImVtYWlsIjoiZ2F1cmF2QGdtYWlsLmNvbSJ9LCJpYXQiOjE2NTMzMzA0
MTV9.CjMFZmk_-JPkEtKmp0AKE76sd2nzH-pBBfZ8l4JW6eQ
Logging out

JSON Web Token or JWT is an open standard for securely transferring data within
parties using a JSON object. JWT is used for stateless authentication mechanisms for
users and providers, this means maintaining sessions on the client-side instead of
storing sessions on the server. Here, we will implement the JWT authentication system
in NodeJs.

Assuming you've logged in successfully, now you have access to all of the protected
routes. However, how can you log out as a user? Manually clearing the JWT cookies is
one option, however, this is not the best approach to logging out. So we'll need a
logout route, which will send a request to the server to log the user out when they
reach it.

Setting up project: Setup the project to create an application for user Logging:

Step 1: Create the project folder, move into that folder and create an app.js file by
using the below command in the terminal:
mkdir gfg
cd gfg
touch app.js

Step 2: Configure the Node package.json file in the project folder:

npm init -y

Step 3: Install all the required modules:

npm i express jsonwebtoken

Project Structure: This project should look like this:

Example: This example illustrates the logging out as a user using JWT:

Javascript
// Requiring Modules
const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();


const access_token = 'fdlfmexwoifoiwehfxqwhvdswfw';
var token;

const user = {
name: 'gaurav',
age: 25
}

// Protected Route
app.get('/user', auth, function (req, res) {
res.json({ user: user, userInfo: req.user });
});

// Logging in
app.post('/login', function (req, res) {
const value = {
email: '[email protected]',
pass: '123'
}
token = jwt.sign({ value }, access_token);
res.send(token);
});

// Logging out
app.post('/logout', function (req, res) {
token = undefined;
res.send('Logout successfully');
});

// Authorization of JWT function


function auth(req, res, next) {
if (token !== undefined) {
jwt.verify(token, access_token, function (err, verified) {
if (err) return res.status(403).send("Forbidden");
req.user = verified;
next();
})
} else {
return res.status(403).send("You are not logged in");
}
};
// Server is running up
app.listen(3000, function () {
console.log("Server is up at port 3000");
});

Steps to start the application: Write the below code in the terminal to run the
server up:

node app.js

Output:

Auth End Points

OAuth (Open Authorization) is an open standard protocol for authorization of an


application for using user information. In general, it allows a third-party application
access to user-related info like name, DOB, email, or other required data from an
application like Facebook, Google etc. without giving the third-party app the user
password. It is pronounced as oh-auth.

You might have seen a “login with Google” or “login with Facebook” button on the
login/signup page of a website that makes it easier to get using the service or website
by simply logging into one of the services and granting the client application
permission to access your data without giving Password. This is done with the OAuth.

Features of OAuth:

1. OAuth allows you to grant a granular level of access, which means you can
request specific data access while login in from Facebook, Google, etc.
2. It allows for either ready only or both read and write access.
3. Third-party that you're using to authenticate your users should be able to
revoke access at any point on their website.

Setting up project: Setup the project to create an application using OAuth:

Step 1: Create the project folder, move into that folder and create an app.js file by
using the below command in the terminal:

mkdir gfg
cd gfg
touch app.js passport.js
Step 2: Create a views folder in the gfg folder, and make four ejs files as home.ejs,
signup.ejs, login.ejs, and access.ejs:

mkdir views
cd views
touch home.ejs signup.ejs login.ejs access.ejs

Step 3: Configure the Node package.json file in the project folder:

npm init -y

Step 4: Install all the required modules:

npm install express passport passport-google-oauth20 cookie-session

Step 5: Now go to google developer console and generate your credentials.


After this step, we should have a Client Id and Client Secret.

Project Structure: This project should look like this:

Example: This example illustrates how to store passwords securely in the MongoDB
database:
home.ejs
<div>
<h1>GeeksforGeeks</h1>
<a href="/signup" role="button">Signup</a>
<a href="/login" role="button">Login</a>
</div>

signup.ejs
<div>
<h1>Signup</h1>
<form action="/signup" method="POST">
<label for="email">Email</label>
<input type="email" name="username">
<label for="password">Password</label>
<input type="password" name="password">
<button type="submit">Signup</button>
</form>
</div>

<div class="col-sm-4">
<a style="border:1px red solid; padding: 10px;
background-color: red; color: #fff;"
href="/auth/google" role="button">
<i class="fab fa-google"></i>
Sign In with Google
</a>
</div>

login.ejs
<div>
<h1>Login</h1>

<form action="/login" method="POST">


<label for="email">Email</label>
<input type="email" name="username">
<label for="password">Password</label>
<input type="password" name="password">
<button type="submit">Login</button>
</form>
</div>

<div class="col-sm-4">
<a style="border:1px red solid; padding: 10px;
background-color: red; color: #fff;"
href="/auth/google" role="button">
<i class="fab fa-google"></i>
Sign In with Google
</a>
</div>

access.ejs
<div class="jumbotron text-center">
<h1>GFG DASHBOARD</h1>
<p>You've Successfully logged into GFG dashboard!</p>
</div>

<hr>
<a class="btn btn-light btn-lg" href="/logout"
role="button">Log Out</a>

app.js
// Requiring modules
require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require('express-session');
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const findOrCreate = require('mongoose-findorcreate');
const app = express();

app.use(express.static("public"));
app.set('view engine', 'ejs');

app.use(session({
secret: "GeeksforGeeks",
resave: false,
saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

// Connecting mongoDB
mongoose.connect("mongodb://localhost:27017/userDB");
mongoose.set("useCreateIndex", true);

// Creating userSchema
const userSchema = new mongoose.Schema({
email: String,
password: String,
googleId: String,
secret: String
});

userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);

// Creating Collection in mongoDB database


const User = new mongoose.model("User", userSchema);

passport.use(User.createStrategy());

// Serialization of user
passport.serializeUser(function (user, done) {
done(null, user.id);
});

// Deserialization of user
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});

// Using passport for authenticate user


passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID, //Secret String
clientSecret: process.env.CLIENT_SECRET, //Secret String
callbackURL: "http://localhost:3000/auth/google/gfg",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
},
function (accessToken, refreshToken, profile, cb) {
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return cb(err, user);
});
}
));

// Routing the pages:

// GET requests
app.get("/", function (req, res) {
res.render("home");
});

app.get("/auth/google",
passport.authenticate('google', { scope: ["profile"] })
);

app.get("/auth/google/gfg",
passport.authenticate('google', { failureRedirect: "/login" }),
function (req, res) {
// Successful authentication, redirect to access.
res.redirect("/access");
});

app.get("/login", function (req, res) {


res.render("login");
});

app.get("/signup", function (req, res) {


res.render("signup");
});

app.get("/access", function (req, res) {


User.find({ "secret": { $ne: null } }, function (err, foundUsers) {
if (err) {
console.log(err);
} else {
if (foundUsers) {
res.render("access", { usersWithSecrets: foundUsers });
}
}
});
});

// Post requests
app.post("/submit", function (req, res) {
const submittedSecret = req.body.secret;
User.findById(req.user.id, function (err, foundUser) {
if (err) {
console.log(err);
} else {
if (foundUser) {
foundUser.secret = submittedSecret;
foundUser.save(function () {
res.redirect("/access");
});
}
}
});
});

// Logout route
app.get("/logout", function (req, res) {
req.logout();
res.redirect("/");
});

app.post("/signup", function (req, res) {

User.register({ username: req.body.username }, req.body.password,


function (err, user) {
if (err) {
console.log(err);
res.redirect("/signup");
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/access");
});
}
});

});

app.post("/login", function (req, res) {

const user = new User({


username: req.body.username,
password: req.body.password
});

req.login(user, function (err) {


if (err) {
console.log(err);
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/access");
});
}
});

});

// Stating up the server


app.listen(3000, function () {
console.log("Server started on port 3000.");
});

Steps to start the application: Write the below code in the terminal to run the
server up:
node app.js

Output:

Joining Heroku and GitHub

Heroku: It is a cloud-based application deployment and management service. Heroku


works on the container-based design system and these smart containers are known
as dynos. It is a simple and one-stop solution to host any website or server. It runs
applications inside various dynos and each dyno is separated from the other.

Step 1: Download the Windows installer: Download the appropriate installer for
your Windows installation from here according to the system configuration
Step 2: Running the installer to the system: Now, click on the installer file and it
will ask for choosing components from the following options as given below.

Heroku cli
Adding heroku to system path
Adding local data
Make sure that you check all of them. Now click the “Next” button.

Step 3: Setting the destination folder: The default path will be the path of the C
drive of the system. The default path for installation can be changed using the
“Browse” button.
Step 4: Installation: After clicking “Install”, it will start to install Heroku CLI into the
destination folder as shown in the below screenshot:

After a couple of seconds, Heroku CLI will be installed on the system completely.
Heroku CLI has been successfully installed on your system. To verify, run the following
command in the Command Prompt or Terminal.

heroku
Github: Github is a for-profit company owned by Microsoft, which hosts Git
repositories online. It helps users share their git repository online, with other users, or
access it remotely. You can also host a public repository for free on Github.

Introduction to Git: Git is a free and open-source distributed version control


system designed to handle everything from small to very large projects with speed
and efficiency.
What is a Version Control System?

A version Control system is a system that maintains different versions of your project
when we work in a team or as an individual. (system managing changes to files) As
the project progresses, new features get added to it. So, a version control system
maintains all the different versions of your project for you and you can roll back to any
version you want without causing any trouble to you for maintaining different versions
by giving names to it like MyProject, MyProjectWithFeature1, etc.

Installation of Git: Let's now install the Git into your local system:

Step 1: Download and install git in your system using the official website.
Step 2: After Installing, you can check if it is installed properly or not by typing the
following command in the Command Prompt:

git –version

Step 3: Now create an account on GitHub.


Step 4: Configure your Git account with your GitHub. To do this Open Command
Prompt and Type:

git config –global user.name “YourUserNameOnGithub”


git config –global user.email “YourEmail”

Here, replace YourUserNameOnGithub with your GitHub-username,


and YourEmail with the email-id used while creating an account on GitHub.

Step 5: After configuring your details, you can check by using the command, your
GitHub username and email will be displayed, which will make sure that your Git is
linked with your GitHub:

git config –global –list


You have now successfully installed Heroku and Git into your local system.

Version Control with Git

A Version Control system is a system that maintains different versions of your


project when we work in a team or as an individual (system managing changes to
files). As the project progresses, new features get added to it. So, a version control
system maintains all the different versions of your project for you and you can roll
back to any version you want without causing any trouble to you for maintaining
different versions by giving names to it like MyProject, MyProjectWithFeature1, etc.

Git is a free and open-source distributed version control system designed to handle
everything from small to very large projects with speed and efficiency.
What are GIT Repositories: Repositories in GIT contain a collection of files of
various different versions of a Project. These files are imported from the repository
into the local server of the user for further updations and modifications in the content
of the file. A VCS or the Version Control System is used to create these versions and
store them in a specific place termed a repository. The process of copying the content
from an existing Git Repository with the help of various Git Tools is termed cloning.
Once the cloning process is done, the user gets the complete repository on his local
machine. Git by default assumes the work to be done on the repository is as a user,
once the cloning is done.

Benefits of the version control system:

 Enhances the project development speed by providing efficient collaboration.


 Leverages the productivity, expedites product delivery, and skills of the
employees through better communication and assistance.
 Reduce possibilities of errors and conflicts meanwhile project development
through traceability to every small change.
 Employees or contributors of the project can contribute from anywhere
irrespective of the different geographical locations through this VCS.
 For each different contributor to the project, a different working copy is
maintained and not merged to the main file unless the working copy is
validated. The most popular example is Git, Helix core, Microsoft TFS.
 Helps in recovery in case of any disaster or contingent situation.
 Informs us about Who, What, When, and Why changes have been made.

Use of Version Control System:

 A repository: It can be thought of as a database of changes. It contains all the


edits and historical versions (snapshots) of the project.
 Copy of Work (sometimes called checkout): It is the personal copy of all
the files in a project. You can edit this copy, without affecting the work of others
and you can finally commit your changes to a repository when you are done
making changes.
Configure Git account: Configure your Git account with your GitHub. To do this
Open Command Prompt and Type:

git config –global user.name “YourUserNameOnGithub”


git config –global user.email “YourEmail”

Here, replace YourUserNameOnGithub with your GitHub-username,


and YourEmail with the email-id used while creating an account on GitHub.

After configuring your details, you can check by using the command, your GitHub
username and email will be displayed, which will make sure that your Git is linked
with your GitHub:

git config –global –list


GIT Commands: The following are some of the commands available in GIT:

Setup: Configuring user data, initializing and cloning repositories that are shared
across all local repositories

git config --global user.name "YourUserNameOnGithub"

When reviewing version history, give yourself a name that you can remember.

git config --global user.email "YourEmail"

When reviewing version history, give the email address that you can remember.
git init

Create a Git repository from an existing directory

git clone "URL"

Through URL, retrieve the whole repository from a hosted location

Stages: Working with Git staging area

git status

indicate files that have been updated in your working directory and are ready for your
next contribution

git add "file"

to your next contribution, add a file as it is presently

git reset "file"

Reset a file while keeping the working directory changes


git diff

What has changed but has not been staged

Branching & Merging: Isolating work in branches, changing context, and integrating
changes

git branch

Make a branch list. Next to the presently active branch, a * will show.

git branch "branch-name"

At the current commit, create a new branch

git checkout

Change to a different branch and check it into your working directory.

git merge "branch"

Integrate the history of the selected branch into the current one
git log

List all commits in the history of the current branch

Share & Update: Updating local repositories and retrieving updates from another
repository

git remote add "alias" "URL"

As an alias, add a git URL

git fetch "alias"

Obtain all of the branches from the Git remote

git merge "branch"

To bring your current branch up to date, merge a remote branch into it.

git push "branch"

Send commits from the local branch to the remote repository branch.
git pull

Any commits from the tracking remote branch should be fetched and merged

Push code to Github

A version Control system is a system that maintains different versions of your


project when we work in a team or as an individual (system managing changes to
files). As the project progresses, new features get added to it. So, a version control
system maintains all the different versions of your project for you and you can roll
back to any version that you want without causing any trouble to you for maintaining
different versions by giving names to it like MyProject, Ecommerce, etc.

Git is an open-source version control system. It means that whenever a developer


develops some project (like an app or website) or something, he/she constantly
updates it catering to the demands of users, technology, and whatsoever it may be.
Git is a version control system that lets you manage and keep track of your source
code history.

Github basically is a for-profit company owned by Microsoft, which hosts Git


repositories online. It helps users share their git repository online, with other users, or
access it remotely. You can also host a public repository for free on Github.

Prerequisite:
 Git Installed
 Github Account
 Git bash or any Terminal

How to Push Code to Github: Let's follow the below steps one by one to push your
code or complete project to the Github using git:

Step 1: Go to the Github website and click on the new button to create a new
repository.

Step 2: Give the project name, choose between public or private repository, and add
a readme file (optional), then click on "Create Repository".
Step 3: Now Open Git bash, command prompt, or any terminal you have to create a
new repository on the command line:

Move to the project folder that you want to push to the GitHub:

cd "foldername"

Initialize Git into that project folder:

git init

Add all the files or resources which you want to push using the below command:

git add .
Commit that change and add a comment:

git commit -m "first commit v1.0"

Select the branch from which you want to push to code to the Github:

git branch -M main

Get the remote and origin access through the URL as shown in the above image:

git remote add origin https://github.com/[username]/[repo name]

Finally, push the update to the GitHub:

git push -u origin main


Step 3: Now go to that link of the Github website again and hit refresh. You'll see that
all the code had been successfully pushed to your Github repository that you just
created.
Deploying Node.js to Heroku

Heroku is a cloud-based application deployment and management service. Heroku


works on the container-based design system and these smart containers are known
as dynos. It is a simple and one-stop solution to host any website or server. It runs
applications inside various dynos and each dyno is separated from the other.

Prerequisite:

 Heroku
 Git and Github Account
 Node.js installed

To finish the process of deploying the Node.js app to Heroku, we must follow three
steps:

1. Creating Node.js Web Application


2. Pushing the Node.js app to GitHub
3. Deploying the Node.js app to Heroku

1. Creating Node.js Web Application: To demonstrate how to deploy a Nodejs


application, we will first develop an example application to gain a better grasp of the
process.

Setting up project: Setup the project to create a basic application of Node.js:


Step 1: Create the project folder, move into that folder and create an app.js file by
using the below command in the terminal:

mkdir gfg
cd gfg
touch app.js

Step 3: Configure the Node package.json file in the project folder:

npm init -y

Step 4: Install all the required modules:

npm i express

Project Structure: This project should look like this:

Example: This example creates the basic server with Node.js:


Javascript
const express = require("express");
const app = express();

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


res.write("<h1>GeeksforGeeks</h1>");
res.write("
<p>This is a basic Node.js web application</p>
");
res.send();
});

app.listen(3000, function () {
console.log("server is up at port 3000");
});

Output:

2. Pushing the Node.js app to GitHub: Let's follow the below steps one by one to
push your code or complete project to the Github using git:
Step 1: Go to the Github website and click on the new button to create a new
repository.

Step 2: Give the project name, choose between public or private repository and add
a readme file (optional), then click on "Create Repository".

Step 3: Now Open Git bash, command prompt, or any terminal you have to create a
new repository on the command line:
Move to the project folder that you want to push to the GitHub:

cd "foldername"

Initialize Git into that project folder:

git init

Add all the files or resources which you want to push using the below command:

git add .

Commit that change and add a comment:

git commit -m "first commit v1.0"

Select the branch from which you want to push to code to the Github:

git branch -M main

Get the remote and origin access through the URL as shown in the above image:
git remote add origin https://github.com/[username]/[repo name]

Finally, push the update to the GitHub:

git push -u origin main

3. Deploying the Node.js app to Heroku: Follow the below steps to finally deploy
your Node.js web application to the Heroku server and make it live and accessible
from anywhere, anytime:

Step 1: Create a free account on Heroku


Step 2: After completing all processes now login into your account.

Step 3: Click on the “Create new app”.

Step 4: Open the Deploy tab and scroll to the “Deployment method” section of the
tab.

Step 5: Select GitHub as a method. It will show a “Connect to GitHub” option


where we add to provide our GitHub repository. If you are doing it for the first time,
Heroku will ask permission to access your GitHub account you have to permit that.
Here, you can search for your GitHub repository and click connect for creating a
connection.

After that, the Deployment section will show up where you can select pick them up
and deploy or Manual Deployment, click Enable Automatic Deploys.
Step 6: Now we have to tell Heroku that our app is a NodeJS app.

Step 7: Open the Settings tab scroll down and click “Add buildpack”.
Step 8: Select NodeJS from the options and click Save changes. Now, go back to the
Deploy tab, and click Deploy Branch at the bottom.

Step 9: Heroku will take the code and host it. Open the Activity tab and there you
can see the progress:
Step 10: Now open the Setting tab scroll and look for Domain. We can see a URL if
we copy paste and run in the browser, we can see our Deployed App.
This is a straightforward app, we can deploy any advanced project on Heroku
without installing it on our desktop or machine.

Note App

ReactJS is an open-source, component-based front-end library responsible only for


the view layer of the application. It is maintained by Facebook. React uses a
declarative paradigm that makes it easier to reason about your application and aims
to be both efficient and flexible.

In this article, we'll show how to build a note application from scratch that will allow
you to make notes similar to the Google Keep app. The basic version of the note app
will allow us to create notes with the appropriate titles and delete them later if the
task has been completed or else.
Prerequisite:

 The node should be installed


 Basic knowledge of React.js
 Visual Code or any IDE to create and run the application

Basic Setup: You will start a new project using create-react-app so open your
terminal and type:

Step 1: Create a React application using the given command:

npm create-react-app projectname

Step 2: After creating your project, move to it using the given command:

cd projectname

Step 3: In the public folder create index.html and style.css files:

cd public
touch index.html style.css
Step 4: Create a Component folder in the src folder and create all the files mentioned
below:

 App.jsx
 CreateNotes.jsx
 Header.jsx
 Note.jsx

cd src
mkdir components
touch App.jsx CreateNotes.jsx Header.jsx Note.jsx

Project Structure: Your project structure should look like this:

Example: In this example, we will design a Note Application in React.js. Write the
below code in the mentioned files.

App.jsx
import React, { useState } from "react";
import Header from "./Header";
import Note from "./Note";
import CreateNotes from "./CreateNotes";
function App() {
const [notes, createNotes] = useState([]);

function addNote(newNote) {
createNotes(oldNotes => {
return [...oldNotes, newNote];
});
}

function removeNote(id) {
createNotes(oldNotes => {
return oldNotes.filter((noteContent, serial) => {
return serial !== id;
});
});
}

return (
<div>
<Header />
<CreateNotes add={addNote} />
{notes.map((noteContent, serial) => {
return (
<Note
key={serial}
id={serial}
heading={noteContent.heading}
text={noteContent.text}
onDelete={removeNote}
/>
);
})}
</div>
);
}

export default App;

CreateNotes.jsx
import React, { useState } from "react";
function CreateNotes(props) {
const [note, createNote] = useState({
heading: "",
text: ""
});

function handleChange(event) {
const { name, value } = event.target;

createNote(prevNote => {
return {
...prevNote,
[name]: value
};
});
}

function addNote(event) {
props.add(note);
createNote({
heading: "",
text: ""
});
event.preventDefault();
}

return (
<div>
<form>
<input
name="heading"
onChange={handleChange}
value={note.heading}
placeholder="Heading"
/>
<textarea
name="text"
onChange={handleChange}
value={note.text}
placeholder="Write your note here"
rows="3"
/>
<button onClick={addNote}>+</button>
</form>
</div>
);
}

export default CreateNotes;

Header.jsx
import React from "react";

function Header() {
return (
<header>
<h1>NOTE APP</h1>
</header>
);
}

export default Header;

Note.jsx
import React from "react";

function Note(comp) {
function clickButton() {
comp.onDelete(comp.id);
}

return (
<div className="box">
<h1>{comp.heading}</h1>
<p>{comp.text}</p>
<button onClick={clickButton}>-</button>
</div>
);
}
export default Note;

index.html
<!DOCTYPE html>
<html>

<head>
<title>Note App</title>
<link rel="preconnect"
href="https://fonts.googleapis.com">
<link rel="preconnect"
href="https://fonts.gstatic.com" crossorigin>
<link href=
"https://fonts.googleapis.com/css2?
family=Open+Sans&family=Roboto&display=swap"
rel="stylesheet">
<link rel="stylesheet" href="styles.css" />
</head>

<body>
<div id="root"></div>
<script src="../src/index.js" type="text/jsx"></script>
</body>

</html>

style.css
* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: Open Sans;
}

header {
background-color: #4b8742;
}
header h1 {
color: #fff;
font-family: "Roboto";
text-align: center;
padding: 20px 10px;
}

.box {
box-shadow: 0 2px 5px rgb(100, 100, 100);
padding: 10px;
width: 300px;
margin: 16px;
float: left;
}
.box h1 {
font-size: 18px;
margin-bottom: 10px;
}
.box p {
font-size: 1.1em;
margin-bottom: 30px;
}

.box button {
background-color: #4b8742;
color: #fff;
border: none;
width: 30px;
height: 30px;
cursor: pointer;
}

form {
width: 500px;
margin-top: 50px;
margin-bottom: 30px;
margin-left: 16px;
padding: 15px;
box-shadow: 0 1px 5px rgb(100, 100, 100);
}
form input,
form textarea {
width: 100%;
border: none;
padding: 6px;
outline: none;
font-size: 20px;
resize: none;
}
form button {
background: #4b8742;
color: #fff;
border: none;
width: 30px;
height: 30px;
cursor: pointer;
}

Step to Run Application: Run the application using the following command from the
root directory of the project:

npm start

Output:

You might also like