0% found this document useful (0 votes)
0 views28 pages

NodeJs Notes

The document provides a comprehensive overview of backend development, focusing on concepts such as server, application, and databases, including both relational and non-relational types. It also introduces Node.js and Express, detailing their functionalities, features, and how to create servers and manage routes. Additionally, it covers middleware, socket programming, and password hashing, highlighting their importance in building efficient and secure web applications.

Uploaded by

Yash Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
0 views28 pages

NodeJs Notes

The document provides a comprehensive overview of backend development, focusing on concepts such as server, application, and databases, including both relational and non-relational types. It also introduces Node.js and Express, detailing their functionalities, features, and how to create servers and manage routes. Additionally, it covers middleware, socket programming, and password hashing, highlighting their importance in building efficient and secure web applications.

Uploaded by

Yash Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 28

Express Overview

I.BACKEND OVERVIEW
What is Backend?
Any Parts of the Website that the user can’t see, have a lot of logic written and
interact with a database to give the required data to the frontend
The backend of the Website consists of Server Application Database
Server: A server is nothing but a machine connected to a network, and having
an application running on it
Application : Application does the task of receiving requests from Frontend
and giving back responses to Frontend
DataBase: Organized Collection of Data So that data can be easily accessed
and managed
Example : MySqL, DynamoDB,MongoDB
Some backend languages are: Python, PHP, Java, Ruby

What are Various types of Databases?


A.Relational Database/SQL Database
1 Relational database stores data in rows and columns in form of Table
2 It is used to handle data coming in low-velocity,
3 It supports Complex Transactions
4 They are compliant with ACID (Atomicity, Consistency, Isolation, Durability)
Properties
5 Data arrives from one and a few locations
Example: MySQL, PostgreSQL,MariaDB,SQLite
How Data is Stored in a Relational Database System?

Data Stored in MYSQL

B Non-Relational Database/NoSQL Database


1 NoSQL database are non-tabular databases and store data differently than
relational tables. NoSQL databases come in a variety of types based on their
data model. The main types are document, key-value, wide-column, and
graph.
2 It is used to handle data coming in high-velocity.
3 It supports Simple Transactions.
4 NoSQL databases deemphasize the principles of ACID (atomicity,
consistency, isolation, and durability).
5 Data arrives from many Locations.
Example : MongoDB,Dynamodb
How Data is stored in Non-relation Database System?
In MongoDB, data is stored as documents. These documents are stored in
MongoDB in JSON (JavaScript Object Notation) format.

Data Stored in MongoDb

II. INTRODUCTION TO NODEJS


What is Nodejs?
Node.js is an open-source, cross-platform, Javascript runtime environment
built on Chrome’s V8 Javascript engine that executes Javascript Code
outside a web browser.
Open source: Open source mean code that is designed to be publicly
accessible
Cross-Platform: We can run nodejs code on various platforms like Mac,
Windows, or Where javascript is installed, The code we wrote in one machine
can run on another machine.
Run-Time Environment: The runtime environment is just the environment in
which your application is running.
Nodejs is asynchronous and single-threaded in nature

What is a Package?
Package: A package in Node. js contains all the files you need for a module.
Modules: are JavaScript libraries that you can include in your project.

What is npm in Node.js?


NPM stands for Node Package Manager. It provides the following two main
functionalities.
1. It works as an Online repository for node.js packages/modules Where
everyone can share Tools written in Javascript
2. It works as a Command-line utility to install packages, do version
management and dependency management of Node.js packages.
NPM comes bundled along with Node.js installable.
Command used to check npm version
npm --version
NPM helps to install any Node.js module using the following command.
npm install <Module Name>
Example:
npm install express (express node.js framwork)

What is the event loop in node js?


The event loop is what allows Node. js to perform non-blocking I/O operations
— despite the fact that JavaScript is single-threaded
When should we use nodejs and when not?
When to use Node.js
It is ideal to use Node.js for developing streaming or event-based real-time
applications that require less CPU usage such as
1. Game servers :
2. Chat Applications
3. Advertisement and Streaming services
4. Good for a collaborative Environment: The “Event loop” feature of
Node.js enables it to handle multiple events simultaneously without
getting blocked. when people work together
When not to use Node js
Node js is a single-threaded, so we should not use it for cases where the
application requires a long processing time. If the server is doing some
calculations, it won’t be able to process any other requests. Hence, Node.js is
best when processing needs less CPU time.

What are the key features of Node.js?


Asynchronous event-driven All APIs of Node.js are asynchronous. Thus new
requests will not wait for the response from the previous requests.
Fast in Code execution Node.js uses the V8 JavaScript Runtime engine, Node
has a wrapper over the JavaScript engine which makes the runtime engine
much faster and hence process requests with node.js is much faster
Active community For Node.js The active community always keeps the
framework updated with the latest trends in web development.
No Buffering Node.js applications never buffer any data. They simply output
the data in chunks.

How to create a simple server in Node.js?


III EXPRESS OVERVIEW
What is a framework?
A framework works as a kind of support structure for something to be built on
top of.

What is Express?
Express is a framework built on top of Node.

What are the advantages of using Express?


1. With a myriad of HTTP utility methods and middleware , creating a
robust API is quick and easy .
2. Express provides a thin layer of fundamental web application features,
without obscuring Node.js features that you know .
3. Many popular frameworks are based on Express .
4. Express helps you manage everything, from routes to handling requests
5. Open Source Community : It has an open-source community,so the
code is always reviewed and improved .
6. Express Framework is reliable and has a huge community around .

How to install and write code in Express?


Installation
npm i express
get request

post request
IV USING MODULES
What are Modules?
small units of independent, reusable code that is desired to be used as the
building blocks.

What is exports in node.js?


When we want to export multiple variables/functions from one module to
another, we use exports.

What is require in node.js?


In NodeJS, require() is a built-in function to include external modules that
exist in separate files. require() statement basically reads a JavaScript file,
executes it, and then proceeds to return the export object.

How to export modules from separate .js files and import them in
server.js?
Code For Exporting Modules from separate.js Files and importing them in
server.js
Blog.js inside blog_modules

Server.js and output console


V.SERVER ROUTING
Route is url path or pattern
What is Routing and how it works ?
Routing refers how an application responds to a client request to a particular
route, URL, or path and a specific HTTP request method (GET, POST, etc.).
We define routing using methods of the Express object (app) that correspond
to HTTP methods
For example :
app.get() to handle GET requests
app.post() to handle POST requests
app.all() to handle all HTTP methods
app.use() to specify middleware
These routing methods listens for requests that match the specified routes,
and when it detects a match, it calls the specified callback function In these
way routing works .
Example :when app.get() methods listen for request that match with the
route (/list) it calls a callback function and then send the response to the
frontend for a particular route

Routing is defined in this way


MiddleWare &Authentication
I.MIDDLEWARE OVERVIEW
What is Middleware and why developers need middleware?
Middleware is a function that accesses the request object (req), response
object (res), and access next middleware function in application’s request-
response cycle
Or
It’s nothing but a function that runs even before the call goes to the API for
which it is meant to be .
Middleware is needed because
1. Middleware helps developers build applications more efficiently
2. It acts as the connective tissue between applications, data, and users.
3. Middleware functions can perform the following tasks:
• Make changes to the request and the response objects.
• Execute any code.
• End the request-response cycle.
• Call the next middleware in the stack.
Middleware Function
All middleware functions in Express.js accept three arguments following the
Request, response, and next.

The first argument,req, is shorthand for the request object with built-in
properties to access data from the client-side and facilitate HTTP requests.
The res argument is the response object with built-in methods to send data to
the client-side through HTTP requests.
The argument, next, is a function that tells Express.js to continue on to the
following middleware you have configured for your application.

What is ‘next’ in ExpressJs? And How it works ?


‘next’ is a parameter that is passed in middleware function to pass control to
the next middleware,(if next middleware exists) else it will take to the api from
which call is come to the server .

Can middleware be able for error handling, Explain error handling


in ExpressJs ?
Middleware is able to handle error handling in ExpressJs. This can be done by
passing extra error-handling parameter (err) in the middleware function.
Syntax .
What are different ways of using middleware?
Using middleware at application level with app.use()

Router Level Middleware


II ROUTING MIDDLEWARE
What is Express.Router() ?
It is a function used to create a new router object. This function is used when
we want to create a new router object in our program to handle requests .
Using middleware we can also redirect our request to some pages
When we have to handle a lot of routings in our server.js due to which in
server.js there will be a too much of code ,To get rid out off these we can
create individual files and then using Middleware in our server.js we can reach
to individual created files(or that particular route)

How to use Middleware to redirect requests to other Pages ?


Folder Structure

Files : server.js,contestroutes.js,practicseroute.js
Output
/practicse/mocktesthtml

/practicse/mocktestcss

/practicse/hiringcontest

III HASHING PASSWORD


What is Hashing Password?
Hashing turns your password (or any other piece of data) into a short string of
letters or numbers using an encryption algorithm. If a website is hacked, the
hackers don't get access to your password

What is bcrypt?
Bcrypt is a popular and trusted method for salt and hashing passwords

What are encryption and decryption?


Encryption is the process of translating plain text data (plaintext) into
something that appears to be random and meaningless (ciphertext).
Decryption is the process of converting ciphertext back to plaintext.

Different methods of Hashing password : PBKDF2, bcrypt or scrypt,

What is Salt in bcrypt ?


A salt is a random string that makes the hash unpredictable.

Why do we use bcrypt?


Faster the algorithm is, Faster to break the password
Since BCRYPT is a slow algorithm, it has decryption slowly . Hence hackers will
not crack password easily .
Installation bcrypt
npm i bcrypt

What is salt Round in bcrypt?


"salt round" actually mean the cost factor.
The cost factor controls how much time is needed to calculate a single bcrypt
hash.
The higher the cost factor, the more hashing rounds are done. Increasing the
cost factor by 1 double the necessary time.

What are different ways to hash password through bcrypt?


There are two ways to hash password through bcrypt
1. Generate salt and then Generate hashed password
2. Generate hashed and password together
Generate Salt and then generate password
Generate hashed and password together

What is bcrypt.compare()?
This method compares hashed and plaintext passwords without the salt
string
Socket Programming
I. INTRODUCTION TO SOCKET PROGRAMMING
What is Socket Programming?
A socket Programming is a endpoint of two way Communication link between
two programs running on the network . A socket is bound to a port number so
that the TCP layer can identify the application that data is destined to be sent
to .

What is tcp?
TCP stands for Transmission Control Protocol a communications standard
that enables application programs and computing devices to exchange
messages over a network
OR
TCP is one of the basic standards that define the rules of the internet and is
included within the standards defined by the Internet Engineering Task Force
(IETF).

What is IP?
Every device has an IP address The Internet Protocol (IP) is the method for
sending data from one device to another across the internet. Every device
has an IP address that uniquely identifies it and enables it to communicate
with and exchange data with other devices connected to the internet.

What is the difference between http connection and webSocket


Connection?
Http connection :
1. It is unidirectional where client sends request and server send response
2. Example client send the request , corresponding to that request server
send the response , after sending the response connection get
terminated
3. If a user is sending 100 requests then corresponding to each request
server sends a response and each http and https request establishes
the new connection to the server every time and after getting the
response the connection gets terminated by itself.
4. Stateless Protocol: Stateless Protocols are the type of network protocols
in which the Client sends a request to the server and the server
response back according to the current state
WebSocket Connection :
1. It is a bidirectional full-duplex protocol.
2. whenever we initiate the connection between client server the client-
server made the handshaking and decide to create a new connection
and this connection will keep alive until terminated by any of them.
3. In websocket conection , connection will not terminate after a single
request response
4. Stateful Protocol: A Stateful Protocol is a type of network protocol in
which the client sends a server request and expects some sort of
response. In case it doesn't get a response, it then resends the intended
request

Where do we use Socket Programming ?


It is used in various Apps Like Chat App , Game App , Notification Engine

What are the advantages and Disadvantages of Socket


Programming?
Advantages:
1. Socket is flexible and sufficient.
2. Efficient socket-based programming can be easily implemented for
general communications.
3. It causes low network traffic.
Disadvantages:
1. Socket-based communication allows only to send packets of raw data
between applications. Both the client-side and server-side have to provide
mechanisms to make the data useful in any way.

II BUILDING SOCKET CONNECTIONS


Installation
For building Socket Connections
Frontend - npm install socket.io-client
Backend - npm install socket.io
What is Socket.io?
Socket.IO is a library that enables real-time, bidirectional, and event-based
communication between the browser and the server.

What is Socket in Socket.io?


A Socket is basically an EventEmitter that sends events to — and receives
events from — the server over the network.
What are event Listeners?
An event listener is a function in JavaScript that waits for an event to occur.
And after the event occurred there will be a certain set of actions(Whatever
we have defined in our code) executed.

Event Listeners in Nodejs are the same as the callback. A callback function is
called when a function execution is completed

Whenever we hit /request on the browser, there will be a callback, according


to /request response, we will send the response to our frontend
also, event listeners work when any specified event has fired

List Some EventEmitter methods ?


socket.emit - This method is responsible for sending messages.
socket.on - This method is responsible for listening for incoming messages.
socket. off(eventName, listener) - Removes the specified listener from the
listener array for the event named eventName.
socket. once(event name, event listener) - Adds a one-time listener for the
event, after which it is removed. This listener is invoked only the next time the
event is fired.
socket.removeAllListeners("event") - Removes all listeners.

Code For Setting Connection between Client Side and Server-side


in socket Programming
The frontend and backend will run on a different port
Frontend

Backend

Connections
III EVENTS IN SOCKET PROGRAMMING
• The Interactions between client and server happen through events .
• One party emit an event and another party will listen .
• And another party do the actions whatsoever the event emitted .

Case when Frontend (Client) and backend (server) both are emitting event
Frontend Code
Backend Code

Browser
Case : Broadcast Message When all the clients connected to the server
received the server event
Frontend Code
Backend Code

Browser

IV ROOMS IN SOCKET PROGRAMMING

Case: only those users who have joined the room received the message
when any of the room member from the Room send the message(Group
Chat)
Frontend Code
Backend Code
Browser

You might also like