[go: up one dir, main page]

0% found this document useful (0 votes)
9 views47 pages

Mongodb, Express, and Nodejs Notes: What Is Node Js and Why We Use Node Instead of Other Technology ?

The document provides an overview of Node.js, explaining its role as a JavaScript runtime that allows for server-side execution outside of the browser, and highlights its advantages such as speed and scalability for data-intensive applications. It discusses the asynchronous and non-blocking nature of Node.js, the importance of using modules, and the creation of a simple web server and API. Additionally, it covers npm for package management, the structure of package.json, and the basics of backend development and DNS interactions.

Uploaded by

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

Mongodb, Express, and Nodejs Notes: What Is Node Js and Why We Use Node Instead of Other Technology ?

The document provides an overview of Node.js, explaining its role as a JavaScript runtime that allows for server-side execution outside of the browser, and highlights its advantages such as speed and scalability for data-intensive applications. It discusses the asynchronous and non-blocking nature of Node.js, the importance of using modules, and the creation of a simple web server and API. Additionally, it covers npm for package management, the structure of package.json, and the basics of backend development and DNS interactions.

Uploaded by

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

Mongodb,

Express, and
Nodejs
NOTES
What is node js and why we use node
instead of other technology ?
Node.js is a javascript runtime built on google’s open-source v8
javascript engine.
We already use javascript before and but inside the browser because
any browser understand html, css and javascript no matter if its vanilla
js or react code , all gets executed right in the browser , then the
browser is then the javascript runtime BUT what if we could take
javascript out of the browser and simply execute javascript code
somewhere else without all the restrictions that we have in the browser
well we actually can with the help of node.js

Node js is just like the container like an environment in


which a program written in javascript can be executed
but outside of any browser whatsoever,
Who execute the javascript code if not the browser ?
That the v8 engine developed by google comes into play
because that is where the javascript code is parsed and
run in nodeJs
JavaScript on the Server
Why and When to use node.js ?
1. Node applications are so fast and so scalable because nodejs is
single threaded, based on event driven, non-blocking I/O model
which makes nodejs very lighweight and efficient.
2. Perfect for building fast and scalable data-intensive web
applications and that makes nodejs a perfect fit for building all
different kinds of applications like building an API with database
behind it(preferably NoSQL), Data streaming (yt,netflix), Real-time
chat Applications, Server-side web applications.

3. Javascript across the entire stack : faster and more efficient


development.

4. NPM: huge library of open-source packages available for everyone


for free;

Where not to use nodejs ?


Node.js is a versatile and powerful server-side JavaScript runtime that can be
used to develop a wide range of applications, including web applications,
mobile applications, desktop applications, and even IoT applications.
However, there are some types of applications that may not be suitable for
Node.js:

1. CPU-Intensive Applications: Node.js is not well-suited for applications


that require heavy CPU usage, such as video rendering, machine
learning, or scientific computing. This is because Node.js is single-
threaded and event-driven, and it can be slow when it comes to
processing complex CPU-intensive tasks.
2. Real-Time Applications: Node.js is not the best choice for real-time
applications that require high-speed, low-latency communication,
such as online gaming or chat applications. While Node.js can handle
real-time applications, it may not be as efficient as other technologies,
such as WebSocket or Socket.IO.
3. Memory-Intensive Applications: Node.js may not be the best choice for
applications that require a lot of memory usage, such as large-scale
image processing or video streaming applications. While Node.js can
handle such applications, it may not be as efficient as other
technologies, such as C++ or Java.
4. High-Security Applications: While Node.js can be used to develop
secure applications, it may not be the best choice for high-security
applications that require a high level of security and protection
against cyber threats. In such cases, it is recommended to use other
technologies, such as Java or .NET.
Running JavaScript outside
the browser
To interact with node we write node in terminal
Interaction with the node

_ denotes previous result.

Ctrl + k to clear the console.


Ctrl + d to exit the rapel.
Using modules 1 core Modules
to run javascript file in terminal type node index.js
// reading files from the file system
// in order to do that we use node module, node.js is
really built around this concept of modules where all
kind of additional functionality are stored in modules

// and in case of reading files that is inside the


fs(file system) module

// by using this module here we will get access to


functions for reading data and writing data right to the
file system
const fs = require("fs");

// this will return an object in which there are lot of


functions that we can use and we store that object right
to fs variable
Reading and writing files (synchronous
way)

// 1. Read file

const fs = require("fs");
// it takes two arguments the first one is the path to
the file that we are reading and then also the character
encoded
const textIn = fs.readFileSync("./txt/input.txt", "utf-
8");
console.log(textIn);

// 2. Write file

const textOut = `This is what we know about avacado: $


{textIn}
. \nCreated on ${Date.now()}`;

fs.writeFileSync("./txt/output.txt", textOut);
console.log("File written!");
Blocking and Non-
blocking:
Asynchronous Nature
of Node.js
·
Synchronous Code in Node.js:
 Code executed line by line, waiting for each statement to complete before moving on.
 Blocking nature can lead to inefficiencies, especially with slow operations.
· Asynchronous, Non-blocking Code in Node.js:
 Solution to blocking code issues in Node.js.
 Involves uploading heavy work to the background, allowing the rest of the code to
continue executing.
 Utilizes callback functions to handle results once background tasks are complete.
· Single-Threaded Nature of Node.js:
 Node.js processes operate on a single thread.
 All users accessing an application share this thread.
 Synchronous code execution can lead to delays for other users.
· Callback Hell:
 Nested callbacks can make code hard to read and manage.
 Triangular shape in code structure is a sign of callback hell.
· Use of Callbacks in Asynchronous Code:
 Callbacks are essential for handling asynchronous operations effectively.
 Callback functions are registered to process results once background tasks are finished.
· Callback Hell Escape:
 More advanced tools like ES6 promises and ES8 async/await provide elegant solutions.
 However, the course focuses on callbacks, aligning with Node.js's original design.
· Practical Implementation:
 Demonstrated asynchronous behavior with the example of reading a file using the
readFile function.
 Emphasized the importance of avoiding blocking code for a better user experience.
· Future Topics:
Promised a deeper understanding of how Node.js handles asynchronous code under the
hood in the next section.
 Mentioned an optional section on promises and async/await later in the course.
· Overall Goal:
 Emphasized the need for asynchronous, non-blocking code to build highly performant
and scalable web applications in Node.js.
 Acknowledged the challenges of callback hell and introduced more advanced tools as
potential solutions.

Reading and writing


files (Asynchronous
way)
fs.readFile("./txt/start.txt");
in this we don’t have to specify the file encoding like utf-8 and instead it will
be a callback function

node will start reading the file in the background and as soon as it is ready it
will start the callback function, the callback function takes two arguments
the one is error and the second one is actual data

// Non-blocking, Asynchronous code


fs.readFile("./txt/start.txt", "utf-8", (err, data1) => {
fs.readFile(`./txt/${data1}.txt`, "utf-8", (err, data2)
=> {
console.log(data2);
fs.readFile(`./txt/append.txt`, "utf-8", (err, data3)
=> {
console.log(data3);

fs.writeFile("./txt/final.txt", `${data2}\n$
{data3}`, "utf-8", (err) => {
console.log("Your files has been written🥳");
});
});
});
});
console.log("Will read file!");

incase of error changing the first callback function , just mistyping startttt
// Non-blocking, Asynchronous code
fs.readFile("./txt/starttttt.txt", "utf-8", (err, data1)
=> {
if (err) return console.log("ERROR!💀");

fs.readFile(`./txt/${data1}.txt`, "utf-8", (err, data2)


=> {
console.log(data2);
fs.readFile(`./txt/append.txt`, "utf-8", (err, data3)
=> {
console.log(data3);

fs.writeFile("./txt/final.txt", `${data2}\n$
{data3}`, "utf-8", (err) => {
console.log("Your files has been written🥳");
});
});
});
});
console.log("Will read file!");
Creating a
simple web
server
Capable of accepting request and capable of
sending back responses..

In order to build server we need two things : -


1. We create a server and then we can start the
server to listen incoming request.
Createserver will accept a callback function which
will be fired off each time a new request hit on
server..

And this callback function gets access to two


very important and fundamental variables.

It is the request variable, and a response


variable.

1. The request object will all have


access to request object which hold all
kinds of stuff like request URL and
bunch of other step.

2. The response object will give us lot


of tools basically with dealing with
response , for sending out the
response

And this end is the very simple of sending


responses.
Creating the server was the first part ,
the second part is to listen for incoming
requests from the client

Output

We created our server using createServer and pass


in the call back function that is executed each time
that a new request hits the server, and
then we started listening for incoming
requests on the local host IP, and then on
port 8000. Once we had all this running,
we actually did the request by hitting that
url. So basically by hitting local host on
port 8000. So then, under the hood of
NoteJS an event was fired which is
something that, again,
we're going to talk about a bit later. But
what matters here is that this event then
made it so this callback function was
called. And finally as a result of that, we
then got back this string.

Routing
Routing means implementing different actions for
different urls.
Http header is basically a piece of information
about the response that we are sending back.
Implementing Routing
in this server
Requesting from URL .

When we using the browser the browser automatically


performs a request for the website favicon. The second doesn’t
really matter.
Besides sending 404 status code we can also send
headers.
A http header is basically a piece of information
about the response that we are sending back.

The browser is now expecting a html .


These headers are always and also the status code
are always send out before we send the response.

Creating a simple web


api
An api is a service from which we can request some
data, the data that the user wants to request.

And Json is a text format that looks a lot like


javascript object.

This dot is not always the ideal there is a better way


All node.js scripts they get access to a variable
called dirname and that variable always translate to
the directory in which the script that we are
currenly executing is located.
fs.readFile(`${__dirname}/dev-data/data.json`);
whenever we send JSON we write
// /////////////////////////////
// SERVER

const data = fs.readFileSync(`${__dirname}/dev-data/data.json`, "utf-8");


const dataobj = JSON.parse(data);

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


// Routing
const pathname = req.url;
if (pathname === "/" || pathname === "/overview") {
res.end("This is the overview!");
} else if (pathname === "/api") {
res.writeHead(200, { "Content-type": "application/json" });
res.end(data);
} else if (pathname === "/product") {
res.end("This is the product!");
} else {
res.writeHead(404, {
"Content-type": "text/html",
});
res.end("<h1>Page not found!</h1>");
}
});

server.listen(8000, "127.0.0.1", () => {


console.log("Listening on request on port 8000");
});
Create our own modules
In node.js every single file is treated as a module

Introduction to npm and package.json


Npm is a software that is basically to manage the 3rd
party open source packages that we choose to
include and use in your project.

Types of packages and


installs
Two types of packages that we can install is simple
dependency or development dependency.

1.Simple dependency or regular dependency are


simple packages that contain some code that
we include in our own code so code upon which
we built our application and that we call them
dependency.
Slugify : - is a small tool that we can make more
readeable URL out of names

2. Development dependency : - These are some


tools for development for example like a code
bundler like web pack or a debugger, they are
not needed for production so our code does not
depend on them we simply use them to develop
our application.

And to run type : - nodemon index.js

Nodemon is a tool that help us develop node js


applications by automatically restarting the node js
server whenever we change some file in our
working directory
Using Modules: our own
modules
We can create our modules and export like functions and
import the function into other module and use this function.

In node js every single file is treated as modules.


Exporting modules

and import in top of file.


Intro to NPM
Npm init to start the file.
Package.json is a file which contains the details
of the project.
And follow the instructions and then we get the
package.json file.
rd
Using Modules: 3 party
modules
Slugify is a function which we can use to create slugs..
Slug is just last part of the url that contains a unique string that
indentify the resource that the website is displaying.

const slugify = require("slugify");

Package version and updating

Most of the packages in the npm follow the


semantic version notation which means their
version number always expressed with these
3 numbers
1. First one is called major version and
second one is called minor version and
third one is called patch version , the
patch version is always intended to fix
bugs as the patch version improves the
number of patches increases 1,2,3 etc.

2. The minor version introduces some


features into the package, but it does not include breaking changes.
All the changes that are done in a new version number will always be
backward-compatible.
For example :-
If one day the nodemon team, for example, decides to release version
1.19,
well, that will then include some new features but it will not break our
code.

2. Major version which is only bumbed


up whenever there is new huge release
which can have breaking changes.
For example if slugify 2 comes around
then the whole code will broke.

First thing we want to do to check if there


is any outdated packages.…
Npm outdated
If there is no response in command it
means all are updated.

Next we can install certain package with


certain version number for example :-
npm install slugify@1.0.0

And then we want to update npm update


slugify

Deleting Packages
Npm unistall express(whatever the
package name is)
Sharing the code without the node
modules
All we have to do is npm install
Suppose we have a file without the node
modules folder , all we have to do is npm
install.

Introduction to
Backend
Development
How the web works behind the scenes ?
Lets say we want to access google
maps by writing
www.google.com/maps into the
browser.

And every website link has a http or


Https protocol that is used for the
connection.
And then we have domain name which
in this case is google.com and also
after a slash a resource page which is
called maps.

Need to know
1. The domain name like google.com
is not actually the real address of the
server which we are trying to access.
2. Browser need to convert the
domain name to the real address of
the server and that happens through
DNS .
3. DNS stands for domain name
server which are special server that
are basically like the phonebook of the
internet.
4. So the first thing that happens
when we opens a website is the
browser makes request to the DNS.
5. Then the DNS server matches the
address of the domain name that we
typed in the browser to the server real
address and this happens through ISP.
6. Once we have the real address A
tcp connection is established between
the browser and server which is now
finally connected.
And this connection is kept alive for
the entire time it takes to transfer all
the files of the website.
What is TCP/IP ?

TCP stands for


transmission control
protocol and Ip stands
for internet protocol.
And together they are
communication protocol
that defines how data
transfer across the web
so they are internet
control system.

Now its finally time to make request ,


and request we made is http request
, it stands for hyper text transfer
protocol.

After tcp / ip , http is yet another


communication protocol and
communication protocol is the
system of rules that allows two or
more party to communicate.
And in the case of http, its just a
protocol that allows client and web
server to communicate by sending
response and request messages from
client to server.

Get for requesting data and put and patch to


modify the data.
The main difference between http and https
request is that https is encrypted using tsl and ssl
which are some protocol.
And after that the website is rendered.

The job is tcp is break the request and


responses into thousands of small chunks
called packets before they are sent, once
they get to their destination , it will resemble
all the packets into the original request and
response so the message arrive at the
destination as quick as possible.
Which would not be possible if we send the
website as one big chunk.
Front end vs backend
Front-end Development:

 Concerned with what happens in the web browser.


 Involves designing and building the visible website.
 Utilizes HTML, CSS, and JavaScript.
 Additional technologies like React, Angular, Redux, GraphQL may be
used.
 Technologies used collectively are referred to as the front-end stack.

Back-end Development:

 Involves processes on the web server, invisible to the user.


 Basic server stores website files and runs an HTTP server.
 The HTTP server communicates with the browser using requests and
responses.
 Static servers serve static files; dynamic servers handle dynamic
applications and databases.
 Dynamic web applications often require interaction with databases.
 Typical back-end tasks include user profiles, logins, email sending,
payment handling, database manipulation, etc.

Back-end Stack:

 NodeJS used as a dynamic web server.


 MongoDB commonly used as the database.
 Various other technologies available, such as PHP with MySQL, Python
with PostgreSQL, Ruby on Rails, etc.

Full Stack Development:

 Combines both front-end and back-end stacks.


 Full stack developers are proficient in both areas.

Scope of NodeJS:

 Primarily applied to back-end web development, not hardware


programming.
 Can be used for IoT devices, drones, robots, etc., but not covered in
this course.

Conclusion:

 Understanding the distinction between front-end and back-end


development is crucial.
 NodeJS finds application in real-world web development scenarios.
Static Vs
Dynamic Vs API
Lecture Important Points:

1. Static vs Dynamic Websites:


 Static websites: Final files uploaded to the server, no server-side
processing.
 Dynamic websites: Built on the server each time a request
comes in, involve server-side processing and database
interactions.
2. Server-Side Rendering:
 Dynamic websites are often generated dynamically on the
server-side, termed as server-side rendering.
 Content changes based on data from databases or user actions.
3. Web Applications:
 Dynamic websites with additional functionality like user
authentication, data search, etc.
 Traditionally, dynamic websites and web applications are used
interchangeably.
4. API-Powered Websites:
 APIs (Application Programming Interfaces) allow communication
between software applications.
 API-Powered websites send only data (usually in JSON format) to
the client, not entire web pages.
5. Client-Side Rendering:
 Websites assembled on the client-side by plugging received data
into templates.
 Front-end frameworks like React, Angular, or Vue commonly
used.
6. Node.js for APIs:
 Node.js is ideal for building APIs due to its non-blocking I/O model
and event-driven architecture.
 APIs can be consumed by various clients beyond web browsers,
including mobile apps and desktop applications.
7. Advantages of APIs:
 APIs decouple the data source from the presentation layer,
allowing flexibility in client types.
 Enables reuse of data across multiple platforms and applications.
8. Business Applications:
 APIs are crucial for complex products requiring multiple apps and
platforms.
 Some businesses solely sell access to their APIs, catering to
third-party developers and companies.
9. Philosophy of APIs:
 APIs enable data accessibility and interoperability across diverse
platforms and applications.
 Entire businesses are built around the concept of selling API
access.
10. Course Approach:
 Course covers both API development and server-side rendered
websites using Node.js.
 Importance of understanding both approaches emphasized for
comprehensive web development skills.

These points highlight the distinction between static and dynamic websites,
the role of APIs in modern web development, and the significance of Node.js
in building dynamic, data-driven applications. Understanding these concepts
is crucial for proficient back-end web development.
How Node.js
works behind
the scenes

1. Node.js Dependencies:
 Node.js runtime relies on several dependencies to function
properly.
 The two primary dependencies are:
 V8 Engine: Developed by Google, V8 is crucial for
interpreting JavaScript code and converting it into machine
code.
 libuv: An open-source library focused on asynchronous I/O
operations, providing Node.js access to the underlying
operating system, file system, networking, etc.
2. V8 Engine:
 Responsible for converting JavaScript code into machine code
understandable by the computer.
 Fundamental part of Node.js architecture, enabling it to execute
JavaScript code.
3. libuv:
 Written in C++, libuv facilitates asynchronous I/O operations.
 Implements critical features like the event loop and thread pool,
essential for Node.js functionality.
 Handles tasks such as executing callbacks, network I/O, file
access, and more.
 Provides a layer of abstraction for developers, making it easier to
interact with low-level system functionalities.
4. Event Loop and Thread Pool:
 Event loop: Manages tasks like executing callbacks and handling
network I/O.
 Thread pool: Handles heavier tasks such as file access and
compression.
 These concepts will be elaborated on in subsequent lectures.
5. Node.js:
 Written in both C++ and JavaScript, Node.js amalgamates
various libraries into a cohesive runtime environment.
 Offers developers access to low-level functionalities through
high-level JavaScript APIs.
 Provides a seamless experience for developers, abstracting away
complexities of underlying C++ code.
6. Additional Dependencies:
 Apart from V8 and libuv, Node.js relies on other libraries for
specific tasks such as HTTP parsing, DNS requests,
cryptography, and compression.
 While these dependencies are crucial for Node.js functionality,
they are less significant for understanding the overall
architecture.
7. Conclusion:
 Node.js seamlessly integrates various dependencies to offer
developers a robust server-side runtime environment.
 Developers can write pure JavaScript code while leveraging the
underlying C++ implementations for efficient execution.
 Understanding the architecture enables developers to harness
Node.js effectively for building server-side applications.
Node Process
and threads
When we use node on a computer
it means a node process is
running on that computer.
And a process is just a program in
execution and node js is just a c+
+ program.

You might also like