Node Js
Node Js
6 Articles
Learn
Fundamentals
6 Articles
Learn
3 Articles
Learn
HTTP Module
5 Articles
Learn
1 Article
Learn
Web Servers
3 Articles
Learn
7 Articles
Learn
6 Articles
Learn
Application Deployment
4 Articles
Learn
Mini Project
1 Article
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.
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".
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.
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:
Here, module_name will be the name of the module that you want to install in your
Node.js application.
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:
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
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.
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:
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.
Javascript
var superheroes = require('superheroes');
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:
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.
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:
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
Steps to start the application: Write the below code to start the server through
nodemon:
nodemon index.js
Output:
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.
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.
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.
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:
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.
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.
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
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");
}
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.
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);
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.
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)
});
Output:
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.
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.
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')
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}`));
})
})
}
Step to run this application: Write the below command in the terminal to run the
server:
node index.js
Output:
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
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.
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 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.
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.
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.
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 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.
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:
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.
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
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.
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:
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:
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
Javascript
var superheroes = require('superheroes');
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.
npm i marvel-comics-characters
Javascript
var names = require('marvel-comics-characters');
var heroes = names.random(3);
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:
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.
For handling all HTTP methods (i.e. GET, POST, PUT, DELETE etc.) use
app.all() method:
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:
Now add the following lines of code in the above function to perform routing:
Javascript
var http = require('http');
// http header
res.writeHead(200, {'Content-Type': 'text/html'});
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() {
Steps to run the server: Write the below code in the terminal to run the program:
node index.js
Output:
Creating a server
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.
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');
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:
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.
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.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:
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.
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
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.
REST
Method Detail
API
GET /posts Listing all resources
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.
Javascript
const http = require('http');
Start the application: Write the below command in the terminal to run the
application:
node index.js
Output:
Handling Errors
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.
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.
Javascript
var fs = require("fs");
console.log("End of Code");
Output:
In this case, the file does not exist in the system hence the error is thrown.
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:
Javascript
async function f() {
let response = await fetch('http://xyzurl');
}
// f() becomes a rejected promise
f().catch(alert);
Output:
Callbacks
Promises
Async/Await
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:
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;
};
demoPromise();
Output:
Hello Express
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:
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
npm init -y
Javascript
const express = require('express');
const app = express();
});
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.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.
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
npm init -y
Step 6: Now we must specify the location of these views within our file system.
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.listen(3000, function () {
console.log("Server started at port 3000");
})
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');
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
{
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.
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).
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 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.
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.
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
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})
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:
mkdir carDB
cd carDB
Spet 2: Initialize the Node npm init and yes to all the options:
npm init -y
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';
const db = client.db(dbName);
insertDocuments(db, function () {
client.close();
});
});
const insertDocuments = function (db, callback) {
Steps to run the application: Write the below code in the terminal to run the
application
node app.js
Output:
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});
item.save();
Installation: In the above project folder, install the mongoose package using npm:
and require the mongoose in the project using the below line at the top of the code:
Example: The below code is establishing a connection to the MongoDB server and
inserting documents using mongoose:
Javascript
const mongoose = require('mongoose');
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
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.
Step 2: Now you can import the mongoose module in your file using:
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.
Javascript
// Requiring module
const mongoose = require('mongoose');
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.
Javascript
const mongoose = require('mongoose');
const Cars = require('./model.js');
// Inserting Data
const Nios = new Cars({
name: "Grand i10 Nios",
color: "Aqua Teal",
cc: 1145
});
Steps to Run the Application: Write the below code in the terminal to run the
application:
node index.js
Output:
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.
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.
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.
HTTP
/cars /cars/Hyundai
Verbs
Create EndPoints
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}
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
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');
// Creating Schema
const carSchema = {
name: String,
color: String,
cc: Number
};
// Creating collection
const Cars = mongoose.model("Cars", carSchema);
// Setting up routes
app.route("/cars")
newCar.save(function (err) {
if (!err) {
res.send("Successfully added a new car.");
} else {
res.send(err);
}
});
})
Cars.deleteMany(function (err) {
if (!err) {
res.send("Successfully deleted all the cars in carDB.");
} else {
res.send(err);
}
});
});
Steps to run the application: run the following command in the terminal to run the
server up:
node app.js
Output:
CRUD Operations
Installation: Install the mongoose and the express module through npm using the
below command:
npm install express mongoose --save
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.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:
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:
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:
Example: In this example, we are deleting a polo car from the cars collection using
db.collection.deleteOne() method.
db.cars.deleteOne({name: "Polo"})
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
npm init -y
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>
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");
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
});
// GET requests
app.get('/', function (req, res) {
res.render("home");
});
// 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);
}
});
});
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.
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.
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
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>
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;
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
});
// GET requests
app.get('/', function (req, res) {
res.render("home");
});
// 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);
}
});
});
});
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
npm init -y
Example: This example illustrates the creation of user Logging with JWT:
Javascript
// Requiring modules
const express = require("express");
const jwt = require('jsonwebtoken');
// 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
});
}
});
});
// 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(' ');
// 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:
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
npm init -y
Example: This example illustrates the logging out as a user using JWT:
Javascript
// Requiring Modules
const express = require('express');
const jwt = require('jsonwebtoken');
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');
});
Steps to start the application: Write the below code in the terminal to run the
server up:
node app.js
Output:
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.
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
npm init -y
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>
<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);
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);
});
});
// 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");
});
// 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("/");
});
});
});
Steps to start the application: Write the below code in the terminal to run the
server up:
node app.js
Output:
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.
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 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 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.
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:
Setup: Configuring user data, initializing and cloning repositories that are shared
across all local repositories
When reviewing version history, give yourself a name that you can remember.
When reviewing version history, give the email address that you can remember.
git init
git status
indicate files that have been updated in your working directory and are ready for your
next contribution
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 checkout
Integrate the history of the selected branch into the current one
git log
Share & Update: Updating local repositories and retrieving updates from another
repository
To bring your current branch up to date, merge a remote branch into it.
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
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"
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:
Select the branch from which you want to push to code to the Github:
Get the remote and origin access through the URL as shown in the above image:
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:
mkdir gfg
cd gfg
touch app.js
npm init -y
npm i express
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"
git init
Add all the files or resources which you want to push using the below command:
git add .
Select the branch from which you want to push to code to the Github:
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]
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 4: Open the Deploy tab and scroll to the “Deployment method” section of the
tab.
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
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:
Basic Setup: You will start a new project using create-react-app so open your
terminal and type:
Step 2: After creating your project, move to it using the given command:
cd projectname
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
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>
);
}
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>
);
}
Header.jsx
import React from "react";
function Header() {
return (
<header>
<h1>NOTE APP</h1>
</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: