0% found this document useful (0 votes)
15 views29 pages

Backend 2

Uploaded by

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

Backend 2

Uploaded by

Yash Rajput
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

[Link]

so now what if kisi ne glti se ye node_module wala folder hi delete kr dia so we have
to simply write npm install . as inside [Link] we have all the modules that were
used in the project are listed there.
[Link]

so here we don't need to push the this nodemodules as this is installed in the system
accordingly. so while pushing when we want ki ye nodemodule shouldn't be included
in the while pushing the code on to git . so for that we make a file named as .gitignore
and there we write the name of that file jisse hme include nhi krna h .
[Link]
package and module are same thing just names are different .
[Link]

nodemon continously runs the node server . meaning jaise hi hm koi changes karenge
those changes will be visible to us . but without it we have write node.\[Link]
so we have to write - npm install nodemon -g
with this -g this means that we can use nodemon globally.
[Link]
to run this we have to use this command . so here as we wanted ki ye [Link] chle
that's why hmne nodemon .\[Link] likh dia h . so from then onwards if we write
something and then we press ctrl + s . toh wo waali file apne aap se hi run ho jaaegi.
[Link]

node js is single threaded and also async . meaning like suppose node js and js , jaruri
nhi h saari lines sequence m chla de . meaning suppose if line 2 is taking more time to
node will run line 3. and so on
[Link]
here the data will be static.
[Link]

so here can see ki after defining the server we have started the nodemon . and thus
starting the server .
In [Link], require() and createServer() are two fundamental components used for
very different purposes:
require()
What it's used for:
The require() function is a cornerstone of [Link]'s CommonJS module system. Its
primary purpose is to load and include external modules or files into your current
JavaScript code. This enables you to organize your code into smaller, reusable pieces,
promoting modularity and maintainability in your applications.
Usage:
You use require() to import:
. Built-in [Link] modules: These are modules that come pre-packaged with [Link] itself (e.g., http,
fs for file system operations, path for path manipulation, os for operating system information).
. Third-party modules (packages): These are modules you install from the Node Package Manager
(npm).
. (You would first install 'express' using npm install express.)
. Your own custom modules/files: You can create your own JavaScript files and export functionality
from them, then require() them in other files.
 [Link]:
 [Link]:
Key characteristics of require():
 Synchronous: When you call require(), [Link] pauses the execution of your code until the module
is fully loaded.
 Caching: Once a module is loaded via require(), [Link] caches it. Subsequent require() calls for
the same module will return the cached version, improving performance.
 CommonJS standard: It's part of the CommonJS module specification, which is the default module
system in [Link]. (Note: [Link] also supports ES Modules (import/export), which are more
common in modern front-end development and are gaining traction in [Link] as well).
createServer()
What it's used for:
The createServer() method is a function provided by [Link]'s built-in http module. Its
purpose is to create a new HTTP server object. This server object is then
responsible for listening for incoming HTTP requests from clients (like web
browsers) and handling those requests.
Usage:
You typically use createServer() to set up a basic web server in [Link]:
Breakdown of createServer() usage:
. [Link](callbackFunction):
 http: This is the http module you required.
 createServer(): This method returns a Server object.
 callbackFunction: This is a function that will be executed every time the server receives an HTTP
request. It takes two arguments:
 req (or request): An object representing the incoming HTTP request. It provides access to details like
the request URL ([Link]), HTTP method ([Link]), and headers ([Link]).
 res (or response): An object used to build and send the HTTP response back to the client. You use its
methods like [Link] = ..., [Link](), and [Link]() to control the response.
. [Link](port, [hostname], [callback]):
 server: The Server object returned by createServer().
 listen(): This method starts the server, making it listen for incoming connections on the specified
port and (optionally) hostname.
 port: The port number the server will listen on (e.g., 3000, 8080).
 hostname (optional): The IP address the server will bind to (e.g., '[Link]' for localhost, '[Link]' to
listen on all available network interfaces).
 callback (optional): A function that is executed once the server starts listening.
In summary, require() is for bringing code into your file, while createServer() is for
creating a web server that can handle network requests. They often work together, as
you'll require the http module to then use its createServer() method.
[Link]
now we are creating a API . so with first two line we have created the server . and
then as we are sending the data then we have to use respond . and whi agr hm koi data
le rhe hote toh . so here first we have wrote the head and then we have wrote body and
then we have ended .
You've hit upon some core methods for sending responses back to clients in [Link]
HTTP servers. Let's clarify them:
First, it's important to correct a small misunderstanding: there is no [Link]()
method. The content of the response body is typically sent using [Link]() or
[Link]().
Now, let's break down [Link](), [Link](), and [Link]() (using res as the
common alias for the response object, though it could be response or any other variable
name you choose for the second parameter in your request handler function).
These methods are all part of the [Link] object (the res object in your
(req, res) callback).

[Link](statusCode, [headers])
Purpose: This method is used to send the HTTP status code and response headers
to the client. It's usually the first thing you call when constructing your response.
When to use it: You use [Link]() when you want to explicitly control the
HTTP status code (e.g., 200 OK, 404 Not Found, 500 Internal Server Error) and/or
send custom HTTP headers (e.g., Content-Type, Location for redirects, Cache-Control).
Parameters:
 statusCode (Number): The 3-digit HTTP status code you want to send.
 200: OK
 404: Not Found
 500: Internal Server Error
 302: Found (for redirects)
 ...and many more.
 headers (Object, optional): An object containing key-value pairs for the HTTP headers. The keys are
header names (case-insensitive, but commonly camelCase or kebab-case), and values are their
corresponding string values.
Example:
Important Notes:
 [Link]() can only be called once per response.
 If you don't explicitly call [Link](), [Link] will implicitly set a statusCode of 200 and
Content-Type: text/plain (or infer based on [Link]() data type) when you call [Link]() or
[Link]() for the first time. However, it's good practice to use [Link]() for clear control.

[Link](chunk, [encoding], [callback])


Purpose: This method is used to send chunks of the response body to the client. It's
particularly useful when you have a large amount of data to send, or when you're
streaming data (e.g., a large file).
When to use it:
 When the response body is large and you want to send it in parts.
 When you are streaming data to the client as it becomes available.
Parameters:
 chunk (String or Buffer): The data to send as part of the response body.
 encoding (String, optional): The encoding for the chunk if it's a string (e.g., 'utf8', 'ascii'). Defaults
to 'utf8'.
 callback (Function, optional): A callback function that is called when the chunk has been flushed to
the underlying system.
Example:
Important Notes:
 You can call [Link]() multiple times.
 You must call [Link]() after you have finished writing all parts of the response body to signal the
end of the response.
 [Link]() only writes data to the buffer; [Link]() actually flushes the buffer and closes the
connection (for that specific request).

[Link]([data], [encoding], [callback])


Purpose: This is the most crucial method for completing a response. It signals to the
server that all response headers and body have been sent, and the server should
now consider the response complete and close the connection (or allow it to be kept
alive if HTTP/1.1 and Connection: keep-alive header is used).
When to use it: You must always call [Link]() for every request you handle, even if
you're not sending any body data (e.g., for a 204 No Content response or a redirect).
Failing to call [Link]() will leave the connection hanging, and the client will never
receive a complete response.
Parameters:
 data (String or Buffer, optional): If provided, this data will be sent as the
last chunk of the response
body. If you've already used [Link](), this data will be appended.
 encoding (String, optional): The encoding for data if it's a string.
 callback (Function, optional): A callback function that is called when the response has been
completely sent.
Example (most common usage):
Example (ending without data, e.g., after a redirect):
Key Difference between [Link]() and [Link]():
 [Link](): Writes data to the response stream, but the response is not yet complete. You can call
it multiple times.
 [Link](): Writes optional final data to the response stream and signals that the response is
complete. You can only call it once per response.

In summary:
. [Link](): Sets the HTTP status code and initial headers (optional, but good practice).
. [Link](): Sends chunks of the response body (can be called multiple times).
. [Link](): Sends the final chunk of data (optional) and signals the end of the response. Crucial to call for
every request.
in the body part we can see ki jo data was sent is first converted into the json .

so is it like in vs code with the help of this createserver we are crating a server and
postman acts as a client and we wanted to see that what a user will get when he uses
that api ?
Yes, you've hit on the core concept perfectly!
Here's a precise way to put it:
VS Code (createServer) and Postman (GET/POST/etc.) in Collaboration:
. VS Code and [Link](): Your Server-Side Code
 When you write [Link] code in VS Code (or any code editor) that uses [Link](), you
are writing the server-side application. This code defines:
 How your server will behave.
 What URLs it will listen to (its "endpoints" or "routes").
 What HTTP methods (GET, POST, PUT, DELETE, etc.) it will respond to for each URL.
 What data it will send back ([Link](), [Link]()) and what status codes/headers
([Link]()) it will use for different requests.
 Once you run this [Link] file (e.g., node [Link] in the VS Code terminal), your computer
becomes a server that is "listening" for incoming network requests on a specific port (e.g., port 3000).
. Postman: Your Client-Side Tool for Testing
 Postman acts as a client. It simulates what a web browser or any other application would do when it
wants to interact with your server.
 Instead of writing complex client-side code just to test your API, Postman provides a user-friendly
interface to:
 Specify the URL of your server's endpoint (e.g., [Link]
 Choose the appropriate HTTP method (GET, POST, etc.) for the type of request you want to make.
 Add headers or a request body if needed (for POST, PUT, PATCH requests).
 Send the request to your running [Link] server.
. "What a user will get when he uses that API?" - The Feedback Loop
 This is precisely the point! After you send a request from Postman, your [Link] server processes it
based on the logic you wrote with createServer().
 The response (status code, headers, and body) that your [Link] server sends back is then displayed
in Postman.
 By examining this response in Postman, you can verify:
 Did the server return the correct HTTP status code (e.g., 200 OK, 404 Not Found)?
 Did it send the expected Content-Type header?
 Is the data in the response body exactly what you intended for that particular API call?
So, yes, you're using VS Code to build the "brain" of your API (the server logic), and
Postman to simulate different "user interactions" with that brain to ensure it's
responding correctly. It's an essential part of the API development and testing
workflow.

[Link](200 , {'content-type' : 'application/json'})


what is the meaning of this line . and why the data in json stringify ?
You're asking about two very important concepts in web API development: setting the
Content-Type header and sending JSON data.
Let's break down [Link](200, {'content-type': 'application/json'}) and then
[Link]().

[Link](200, {'content-type': 'application/json'})


Meaning of [Link](200, ...):
 [Link](): As we discussed, this method sets the HTTP status code and response headers.
 200: This is the HTTP Status Code. 200 means "OK" or "Success". It tells the client that the request was
successfully processed by the server and the response contains the requested data (or the result of
the operation).
 {'content-type': 'application/json'}: This is an object defining the HTTP Headers for the
response.
Meaning of {'content-type': 'application/json'}:
This specific header, Content-Type, is incredibly important for communication between
web servers and clients (like browsers, Postman, or other applications).
 Content-Type: This header tells the client what type of data is being sent in the response body. It's like
attaching a label to a package so the recipient knows how to open and interpret its contents.
 application/json: This is the MIME type (Multipurpose Internet Mail Extensions) that specifically
indicates that the data in the response body is formatted as JSON (JavaScript Object Notation).
Why is Content-Type: application/json important?
. Client Interpretation: When a browser or API client receives a response with Content-Type:
application/json, it knows to parse the response body as a JSON string and convert it into a
JavaScript object (or its equivalent in other programming languages). Without this header, the client
might try to interpret the data as plain text, HTML, or something else, leading to errors or incorrect
display.
. API Standardization: It's the standard way to signal that an API is returning JSON data, which is the
most common data interchange format for modern web APIs.
. Error Handling: If the server is supposed to return JSON but accidentally returns HTML, a client
explicitly looking for application/json can detect the mismatch and handle it gracefully (e.g., by
logging an error or displaying a generic error message).
In short, [Link](200, {'content-type': 'application/json'}) means:
"Hey client, I'm sending you a successful response (200 OK), and the data in the body
of this response is a JSON string, so you should parse it as JSON."

Why the data in [Link]()?


This brings us to the second part of your question.
JSON (JavaScript Object Notation):
JSON is a lightweight data-interchange format. It's human-readable and easy for
machines to parse and generate. It's based on a subset of the JavaScript programming
language.
The Problem:
When you work with data in your [Link] server (e.g., from a database, a computed
result), that data is typically in the form of JavaScript objects or arrays.
However, HTTP responses are fundamentally text-based. You cannot directly send a
JavaScript object over the network as the body of an HTTP response. The network
only understands strings (sequences of characters/bytes).
The Solution: [Link]()
 [Link](value, [replacer], [space]): This built-in JavaScript method takes a JavaScript value (usually an
object or an array) and converts it into a JSON string.
Example:
How it fits together in an API response:
In summary:
 You use [Link](..., {'Content-Type': 'application/json'}) to declare to the client
that the data coming is JSON.
 You use [Link]() to convert your actual JavaScript object data into a JSON string, which is
the format suitable for sending over HTTP.
This two-step process ensures that the client correctly receives and understands the
data you're sending from your API.
[Link]
[Link]

so what we did is ki suppose if we have data which is very large toh what we do is ki
we create separate file and there we put all the data and then from there we import the
data using this require and then we use this .
as we can see ki to send data we first create an array of objects . and inside the objects
we have sent all the info. in by making object in key : value pair form .
HTTP status codes are three-digit numbers returned by a web server to indicate the
status of a client's request. They are grouped into five classes, indicated by the first
digit:
 1xx (Informational): The request was received, continuing process. (Less common in daily Browse)
 2xx (Success): The request was successfully received, understood, and accepted.
 3xx (Redirection): Further action needs to be taken to complete the request.
 4xx (Client Error): The request contains bad syntax or cannot be fulfilled.
 5xx (Server Error): The server failed to fulfill an apparently valid request.
Let's look at the specific codes you asked about:
200 OK (Success)
 Meaning: This is the standard success response for HTTP requests. It means the server successfully
processed the request, and the response body contains the data the client asked for.
 When you see it:
 When you successfully load a web page in your browser.
 When an API GET request retrieves data successfully.
 When an API PUT or PATCH request successfully updates a resource and returns the updated resource.
 When an API DELETE request successfully deletes a resource (though sometimes 204 No Content is
used for DELETE).
 Example: You request [Link] and the server sends back a list of products.
The status code would be 200.
201 Created (Success)
 Meaning: This status code indicates that the request was successful, and as a result, a new resource
has been created on the server.
 When you see it:
 Most commonly used after a POST request that results in creating a new entity (e.g., a new user, a
new product, a new blog post).
 It can also be used if a PUT request creates a resource at a URL that didn't previously exist.
 Key characteristic: The response often includes a Location header, which provides the URL of the
newly created resource. The response body might also contain a representation of the newly created
resource.
 Example: You send a POST request to [Link] with data for a new user. If the
user is successfully created, the server would respond with 201 Created and potentially the full
details of the new user, including their unique ID, in the response body.
404 Not Found (Client Error)
 Meaning: This is one of the most well-known error codes. It means the server was able to
communicate with the client, but it could not find the requested resource at the specified URL. The
server itself is working, but the specific page or resource you're looking for doesn't exist.
 When you see it:
 When you type a wrong URL into your browser.
 When a link on a website points to a page that has been moved or deleted.
 When an API request tries to access an endpoint or resource that doesn't exist (e.g., [Link]
[Link]/non-existent-endpoint).
 Important distinction: A 404 error means the resource is not found, not that the server is down. If the
server itself couldn't be reached, you'd typically get a network error, not an HTTP status code.
These three status codes cover some of the most common scenarios in web
communication, signifying a successful retrieval, a successful creation, and a client-
side error (resource not found), respectively.
[Link]
[Link]

so now we want ki jo ye 100 anil likha h ab hme iss input ko lena h file ke ander .
[Link]
so we write this on first line to get what is written on the console .here can see ki on
console we have 2 things written - first is where the node js is installed and the second
is where this [Link] file is stored.
when wriiting [Link](process) - so this process is the object . and then when we
write [Link] so it means argument vector .
[Link]

so can see ki when using [Link] ke ander 2 values toh always rahengi hi. and as
this is array toh with using [ ] this bracket we can access that element .
[Link]
so now we want ki hm console m hi file jo bnani h and uske ander kya text add krna h
wo likh de . so that is written with [Link]
[Link]

so here can see ki nyi file bn gyi and there is text written .
[Link]
so here can see ki now we have written the logic ki when to add the file and when to
remove the file.
fs is
[Link]

so here can see ki to remove the file we only need last 2 parameters .
[Link]
this getting of file name and then printing will be done on console.
so in node we generally are working with the api , database connection and all . toh
there we need ki api se hm file ko read and ye baaki ki cheezen kr paaye toh ussi ke
lie hm ye sb yha seeekh le rhe h .
[Link]

so now here we wanted to create multiple files . we know that this fs - file system is
provided by the node js itself . we have to just can say import it we don't need to
install it . and then will create a file .
[Link]
so now as we wanted to create a file inside this files folder . so what we did is ki we
use another module named as path . so with only -
const dire = [Link](_dirname) so ye hme abhi hm jha h wha ki directory ye file ki
location bhej dega or can say the path where the current script is running. and then we
have added the
'files' . toh ye simply ek string return krdega path ke ander aur kuch nhi .
[Link]

[Link]
so in first photo we are simply using two 2 syntaxes ek toh double quotes ka and
second ye tilde wala . toh upar waale se ye txt file , files wale folder m nhi banegi . so
to make the inside these hm ye second wali photo ko dekhneg .

[Link](`${dir}hello_${i}.txt `, "hi");
so this is how you write with the backticks . where this dir is a variable where we are
storing the current path.
[Link]

so here we want to read the contents of the directory meaning uss particular directory
m kitni files h. toh ussi ke lie we have used readdir.
and then so here first is the path and then second is arrow function which takes two
arguments. so instead of files we can write something else. so here we have got the
names inside array .
[Link]
so like this using forEach we can print each file alag se .

so the question is ki kya hm bahar kisi ka data get kr skte h meaning suppose our
server is running in d drive toh kya hm c drive ka data access kr skte h . ans is no . coz
jha ye node run ho rha hota h toh wo ek server ki tarah bn jata h and then we can't
access the data outside of it .
there are some techniques but not normally .
[Link]

crud opn database ke sath bhi hote h . these opn are also imp when we learn some
library , framework.
[Link]
so this writefilesync is used to create a file . so we know ki when we are working with
th file system toh hme fs ko import krna hota h . and then as we want ki hme ye file
crud name ke folder ke ander bnani h toh uske lie hmne with the help of path module
current path nikal dia and then ye 3rd line m curd wala as string add kr dia thus
making it as a directory. and then simply hmne iss poore ko ek variable ke ander daal
dia and writefilesync ke ander use kr lia .
generally ye hota h ki hm 4th wali line ko 6 ke ander hi likh dete h .
[Link]

so line 7- 8 is used to read the inside of the file .


so without this utf8 hme ye aise buffer krke number milenge . and then after including
this parameter hme uske ander ka correct data mil jaaega .
[Link]
so here we can see ki there are 3 parameters . first path , second text to be added and
third is error if there is error then print
[Link]

now can see ki we have renamed the file . so for that we have given the current path
poora and then we have given wo wala path jo hmne file ko create krne ke time dia
tha . bs yha name is changed.
[Link]
so with this unlink sync the file has been deleted
what is buffer that we have seen while reading the file . so to work nodejs needs some
space . toh ussi thodi space ko buffer kha jata h.

[Link]

[Link]
synchrnous means ki ek time m sirf ek kaam ho hoga. node js is asynchronous and so is js. php is
synchronous.

[Link]

so this is showing the example of asynchronous.


so this setTimeout is used to take some time off meaning ki kuch time ke baad chle . so can see ki
aisa nhi h ki phle start exe chla and then chli toh 3rd wali line bhi pr node ne uske khtm hone ka
wait nhi kia and then turant 7th line chla di.

[Link]
so this example shows the drawback of asynchronous programming language .
so here we can see ki the ans of a+b should be 30 but the ans is 10. so to remove this drawback
we can either use callback or promises.

[Link]

callbacks bhot phle use hua krte the . now we use either promise or async await.

[Link]
so initially what we were doing is ki hm iss settimeout ke ander ye b = 20 kr rhe the jiski wajah se
we got result as 30.
promise takes two parameters. resolve and reject. resolve means ki when hmara saara kaam ho
gya h and reject means ki when there is some error .
so now we have written 30 inside resolve. toh we can pass anything iside this resolve it may be
integer , array or something else . so what this will do is ki jaise hi 2 sec honge ye waiting data ko
30 return kr dega .
so what happens is ki , jb bhi aisa koi kaam ho ki which is taking some time toh uss poore kaam ko
utha kr hm promise ke ander daal denge .
so jaise hi there comes the data and uske baad hm then lga kr uss data ko use kr lenge. toh iss se
ye console jb tk poora data nhi aa jata uss se phle nhi chalega.
in fetch fn wo phle se hi ek promise ke ander hota h isilie hme uske baad simply then lgana hota h
and nothing else .
resolve and reject are indeed the mechanisms for sending data (or an error) out of the Promise.

[Link]

[Link]
so there are these three things call stack , node api and then we have event loop. so initially call
stack ke ander jaaengi cheezen . and as this log is also a function isilie ye bhi call stack ke ander
chla gya . so jaise hi iska kaam khtm hua ye bahar aa gya. now seeing usage of other two.

[Link]

this eg shows the real execution.


so here phle chalega starting up and then finishing up uske baad 0 second and then 2 second.

[Link]
so node js is entirely made of js but there is some part which is made up of c++ . toh jitni bhi
cheezen c++ ki hoti h na wo saari phle node api ke ander jaati h . so this settimeout is also made
of c++ so isilie ye sbse phle gya node-api ke ander . api is not ki jha se data laate h unhe hi sirf api
nhihi kha jata h unhe bhi khte h jha we create a interface b/w two programming language . so here
those two languages are c++ and js.

[Link]

then we moved aage . and thus 0 wala bhi aa gya.

[Link]
so api to queue ye apna alag chlta rhta h . wo phle chalega jo km time le rha hoga. thus 0 got in
callback queue. and tb tk call stack ke ander hmara main wala bhi khtm ho jaaega .

[Link]

[Link]
so the question may arise that jb wo api ko callstack ke ander aana hi tha toh wo direct stack ke
ander kyu nhi aaye ? bcoz for to run they need empty stack not even main function.

The Event Loop: Bringing it all Together 🔁


The Event Loop is the orchestrator that connects the Call Stack, [Link]/Web APIs, and the
Callback Queue. It's a continuous process that ensures non-blocking execution.
. Call Stack Execution: The Call Stack processes all synchronous code.
. API Delegation: When asynchronous operations are encountered, they're delegated to
[Link]/Web APIs.
. Callback Queueing: Once an API completes its task, the corresponding callback function is
added to the Callback Queue.
. Event Loop Check: The Event Loop constantly checks if the Call Stack is empty.
. Dequeue and Execute: If the Call Stack is empty, the Event Loop takes the first callback from the
Callback Queue and pushes it onto the Call Stack for execution.
This cycle allows JavaScript to handle time-consuming operations (like network requests or file
I/O) without freezing the main thread, providing a smooth and responsive user experience or
efficient server operation.

You might also like