KEMBAR78
Node JS | PDF | Domain Name System | World Wide Web
0% found this document useful (0 votes)
6 views34 pages

Node JS

The document is a syllabus for an Introduction to Node.js course, covering topics such as creating HTTP servers, file system operations, and connecting to MongoDB. It explains the unique features of Node.js, including its asynchronous and non-blocking architecture, and contrasts client-side and server-side JavaScript. Additionally, it outlines the workings of DNS, web protocols, and the Node.js event loop, along with practical examples and code snippets for server creation and request handling.

Uploaded by

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

Node JS

The document is a syllabus for an Introduction to Node.js course, covering topics such as creating HTTP servers, file system operations, and connecting to MongoDB. It explains the unique features of Node.js, including its asynchronous and non-blocking architecture, and contrasts client-side and server-side JavaScript. Additionally, it outlines the workings of DNS, web protocols, and the Node.js event loop, along with practical examples and code snippets for server creation and request handling.

Uploaded by

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

Syllabus

Introduction to NodeJS : Overview of NodeJS & Structure of


NodeJS, Create a basic HTTP server by using HTTP Module,
File System in NodeJS - Read, Write, Delete files, Parsing
URLs using URL Module Database. Core modules in NodeJS,
Creating custom modules, Intro to Path module by fetching
data from terminal,
Connectivity with MongoDB : Introduction to NoSQL database,
Difference between SQL and MongoDB, Create & Drop a
database & collection, Overview of supported data types,
Connecting NodeJS with MongoDB by performing CRUD
operations after querying the database.
What is Node.js?
Node.js is a Open Source, Cross Platform, Runtime Environment that allows us to run
JavaScript outside a web browser. Normally, JavaScript runs inside a browser (like Chrome or
Firefox), but Node.js lets us use JavaScript for backend development, meaning we can create
servers, databases, and full applications with it. Node.js uses V8 to run JavaScript outside the
browser.
V8 Engine is a high-performance JavaScript engine developed by Google.
V8+backend=NodeJS.
V8 converts JavaScript into machine code, making execution fast & efficient.
No browser required! Runs JavaScript directly on the system.

Why is Node.js Special?


● Asynchronous & Non-Blocking – Fast, event-driven execution.
● Single-Threaded & Scalable – Efficient for handling multiple connections.
● Built on Chrome’s V8 Engine – High-speed JavaScript execution.
● Cross-Platform – Runs on Windows, macOS, and Linux.
● File System Access – Read, write, and manipulate files using fs module.
● Built-in Modules – Supports HTTP, File System (fs), Streams, etc.
● NPM (Node Package Manager) – Huge ecosystem with 1.5M+ libraries.
● Real-Time & API Development – Ideal for chats, gaming, and RESTful APIs.
Real-Life Example
Imagine you are using an online
food delivery app:

1. You place an order.


2. The server (built with
Node.js) processes your
request.
3. It checks the database to see
if the food is available.
4. It sends back a response
showing your order status.

Node.js is used in Netflix, PayPal,


Uber, and LinkedIn for fast and
efficient applications.
JavaScript on the Client-Side
Client-side JavaScript runs in the browser and is mainly used for:

● Manipulating the DOM – Dynamically update HTML & CSS (e.g.,


document.getElementById()).
● Handling Events – Respond to user actions like clicks, scrolls, and
form submissions.
● Form Validation – Check user input before sending data to the
server.
● Animations & Effects – Create interactive UI elements.
● Fetching Data (AJAX & Fetch API) – Load data asynchronously
without refreshing the page.
● Local Storage & Cookies – Store data in the browser for faster
access.
JavaScript on the Server-Side (Node.js)
JavaScript is not just for browsers—it can also run on servers using Node.js.

● Handles HTTP Requests & Responses – Build web servers with


frameworks.
● File System Access – Read, write, and manage files using the fs module.
● Database Connectivity – Works with MongoDB, MySQL, PostgreSQL,
etc.
● Real-Time Applications – Supports WebSockets for chat apps, gaming,
and live updates.
● API Development – Create REST & GraphQL APIs.
● Process Management – Handles multiple tasks efficiently using
asynchronous programming.
● Security & Authentication – Manages user authentication (JWT, OAuth).
Client-Side vs. Server-Side JavaScript

Feature Client-Side JavaScript Server-Side JavaScript (Node.js)

Execution Runs in the browser Runs on the server (Node.js)

Environment Uses DOM, BOM, Web APIs Uses Node.js modules (fs, http, etc.)

Purpose Handles UI interactions, DOM manipulation, Manages backend logic, databases,


events APIs

File System ❌ No direct access ✅ Can read, write, and modify


Access
files

Database ❌ Needs APIs (AJAX, Fetch) ✅ Direct access (MongoDB,


Access
MySQL, etc.)

Multithreading ❌ Single-threaded (per tab) ✅ Uses event-driven non-blocking I/O

Security Less secure, exposed to users More secure, runs on the backend

Example Use Animations, form validation, fetching APIs, real-time apps,


data authentication
First Node Server
● How DNS Works
● How Web Works
● What are Protocols
● Node Core Module
● Require Keyword
● Creating first Node Server
How DNS Works?
1. User Requests a Website
● When you type www.google.com in your browser, your computer doesn’t understand this name directly.
● It needs to find the IP address of google.com.
2. Browser Checks Local Cache
● First, the browser checks if it already knows the IP address from a previous visit.
● If found, it loads the page directly.
● If not, it moves to the next step.
3. OS Checks System Cache
● The operating system (OS) also maintains a DNS cache.
● If the IP address is found in the OS cache, it is used immediately.
● If not, the request is sent to the DNS Resolver.
4. DNS Resolver (ISP Level)
● If the browser and OS don’t have the IP, the request goes to a DNS Resolver (provided by your Internet Service
Provider - ISP).
● The DNS Resolver starts searching for the IP address.
5. Recursive Query to Root DNS Server
● If the Resolver doesn’t have the IP, it sends a request to Root DNS Servers.
● Root DNS servers don’t store actual domain names but direct the request to the next level (TLD servers).
6. TLD (Top-Level Domain) Server Lookup
● The Root Server directs the query to the TLD (Top-Level Domain) server, which manages
extensions like .com, .net, .org, etc.
● Example: If you're searching for google.com, it is directed to the .com TLD Server.
7. Authoritative Name Server Lookup
● The TLD Server directs the request to the Authoritative Name Server, which holds the actual IP
address of the website.
● This is like going directly to Google’s personal directory to get its IP.
8. IP Address is Returned to Resolver
● The Authoritative Name Server returns the correct IP address (e.g., 142.250.182.78) to the
DNS Resolver.
● The Resolver caches this response for future requests to speed up future lookups.
9. Resolver Sends IP Address to Browser
● The DNS Resolver sends the IP address back to the browser.
● The browser can now connect to the web server and load the website.
10. Website Loads
● The browser makes a request to the actual web server (e.g., Google’s server at
142.250.182.78).
● The server responds by sending the website content (HTML, CSS, JavaScript, images, etc.).
● The webpage is displayed on the browser.
How DNS Works – Like Amazon Product Search

1⃣ Order History (Browser Cache) – If you've bought the product before, Amazon shows it instantly.
➡ DNS: Browser checks if it already knows the website’s IP.

2⃣ Recently Viewed (OS Cache) – If not in order history, Amazon checks recent searches.
➡ DNS: Your computer checks if it remembers the IP.

3⃣ Warehouse (ISP DNS Resolver) – If not found, Amazon asks its warehouse.
➡ DNS: Your ISP’s DNS resolver searches for the IP.

4⃣ Regional Warehouse (Root Server) – If still missing, Amazon checks regional warehouses.
➡ DNS: Root DNS server directs to .com websites.

5⃣ Brand’s Main Supplier (TLD Server – .com) – Amazon contacts Apple’s main supplier.
➡ DNS: .com TLD server directs to Amazon’s official server.

6⃣ Official Amazon Store (Authoritative DNS Server) – Apple confirms stock details.
➡ DNS: Amazon’s DNS server provides the exact IP.

7⃣ Product Delivered (Website Loads) – Amazon shows the product instantly.


➡ DNS: Browser loads the website using the found IP.
How Web Works
1: You Order a Dish (Requesting a Website)
● You walk into a restaurant (open a browser like Chrome or Firefox).
● You check the menu and tell the waiter what you want (enter a website URL like www.example.com).
2: The Waiter (DNS) Finds the Right Kitchen
● The waiter doesn’t cook the food but knows which kitchen to go to.
● They check the address book (DNS) to find out where the dish (website) is made.
● Example: www.example.com → Kitchen at 192.168.1.1
3: The Chef (Web Server) Prepares Your Order
● The waiter goes to the kitchen (web server) and tells the chef (backend system) what you want.
● The chef gathers all the ingredients (HTML, CSS, JavaScript) and cooks the dish (webpage).
4: The Waiter Brings the Dish (Website) to You
● Once the dish is ready, the waiter brings it back to your table (your browser).
● The dish arrives in parts:
○ HTML → The plate and structure
○ CSS → The decoration and presentation
○ JavaScript → The flavor, movement, and interactivity
5: You Enjoy Your Meal (Browser Displays the Website)
● Your dish is served beautifully, and you start enjoying your meal (browsing the website).
● If you want more sauce (dynamic content), the chef can send it without bringing a new plate (AJAX or WebSockets).
Step 6: You Ask for More (User Interaction & Backend Processing)
● Want dessert? You ask the waiter (click a button or fill out a form).
● The waiter runs to the kitchen, and the chef prepares your request (server processes your action).
● New food appears on your table (dynamic website updates).
What are Protocols
A protocol is a set of rules that devices follow to
communicate over the internet. It ensures data is sent,
received, and understood correctly.

Common Protocols & Their Roles:


1HTTP/HTTPS – Loads web pages (HTTPS is
secure).
2 TCP/IP – Breaks data into packets & delivers them
accurately.
3 DNS – Converts website names into IP addresses.
4 FTP – Transfers files between computers.
5 SMTP/POP3/IMAP – Handles email sending &
receiving.
6 WebSockets – Enables real-time communication
(e.g., live chats).
Node Core Module
Module Purpose

fs File system operations (read, write, delete files) 📁


http Create web servers & handle HTTP requests 🌐
path Work with file & directory paths 📂
os Get OS-related info (CPU, memory, hostname) 💻
events Handle event-driven programming 🎟
util Utility functions for debugging & formatting 🛠
url Parse and format URLs 🔗
querystring Work with URL query parameters 🔍
crypto Perform encryption & hashing 🔒
stream Handle streaming data (e.g., files, videos) 📡
Require Keyword
The require keyword is used to import
modules in Node.js.

1 Import Core Modules (built-in)

const fs = require('fs'); // File System


module

2 Import External Modules (installed via npm)

const express = require('express'); //


Express.js

3 Import Custom Modules (your own files)

const myModule = require('./myModule');

4 Import JSON Files

const data = require('./data.json');


const http=require('http');
// http.createServer(function(req,res)
const server = http.createServer((req,res)=>{
console.log(req);
});
First Node Server: const PORT=3000;
server.listen(PORT,()=>{
console.log('Server running on address
Demo: http://localhost:${port}')
});
// function requestListener(req,res){
// console.log(req);
// }
// http.createServer(requestListener);
Request & Response
1. Node Lifecycle & Event Loop
2. How to exit Event Loop
3. Understand Request Object
4. Sending Response
5. Routing Requests
6. Taking User Input
7. Redirecting Requests
Node.js Lifecycle & Event Loop 2. Node.js Event Loop (How Async
Works)
Node.js is single-threaded but asynchronous, using an
event-driven architecture to handle multiple tasks efficiently. The Event Loop is the heart of Node.js, managing async
tasks like I/O operations, timers, and network
1. Node.js Lifecycle (Execution Flow) requests.

1 Start → The application starts executing. Event Loop Phases


2 Import Modules → Built-in, external, or custom modules are
loaded. 1 Timers Phase → Executes setTimeout() &
3 Event Loop Begins → Node.js starts handling asynchronous setInterval().
operations. 2 Pending Callbacks Phase → Executes I/O callbacks.
4 Execute Code → Sync code runs first, async tasks go to the event 3 Idle, Prepare Phase → Internal tasks (rarely used).
loop. 4 Poll Phase → Processes new I/O events (file read,
5 Callbacks & Promises → Async tasks execute when ready. network requests).
6 Event Loop Continues → Keeps running until no more pending 5 Check Phase → Executes setImmediate()
tasks. callbacks.
7 Exit → When all tasks are complete, Node.js process stops. 6 Close Callbacks Phase → Handles close events like
socket closures.
Request & Response in
Node.js (HTTP Server)
In Node.js, when creating a
web server, we handle
requests (from clients) and
send responses (back to
clients). This is done using
the built-in http module.
We can receive multiple
requests on single Thread
with the help of Thread Pool.
Understanding Request Object
const http=require('http');
const server = http.createServer((req,res)=>{
console.log(req.url, req.method, req.headers);
// process.exit() exit from process
});
const PORT=3001;
server.listen(PORT,()=>{
console.log('Server running on address http://localhost:${port}')
});
Understanding Response
const http=require('http');
const server=http.createServer((req,res)=>{
console.log(req.url, req.method,req.headers);
res.setHeader('Content-Type', 'text/html');
res.write('<html>');
res.write('<head><title> Learn NodeJS</title></head>');
res.write('<body><h1> Request and Response</h1></body>')
res.write('</html>');
res.end();
});
const PORT=3000;
server.listen(PORT,()=>{

console.log('Server running on address http://localhost:${port}')


});
//Understanding Routing
const http=require('http');
const server=http.createServer((req,res)=>{
res.setHeader('Content-Type', 'text/html');
console.log(req.url, req.method,req.headers);
if(req.url==='/'){
res.write('<h1>Home page</h1>');
return res.end();
}
else if(req.url==='/about')
{
res.write('<h1>About Us</h1>');
return res.end();
}
else{
res.write('<html>');
res.write('<head><title> Learn NodeJS</title></head>');
res.write('<body><h1> Request and Response</h1></body>')
res.write('</html>');
return res.end();
}
});
const PORT=3000;
server.listen(PORT,()=>{
res.write('<br> <input type="submit"
//Understanding User Input and value="Submit">');
Re-directing res.write('</form>');
const http=require('http'); res.write('</body>')
const fs=require('fs'); res.write('</html>');
const server=http.createServer((req,res)=>{ return res.end();
res.setHeader('Content-Type', 'text/html'); }
console.log(req.url, else
req.method,req.headers); if(req.url.toLowerCase()==="/submit-de
if(req.url==='/'){ tails" && req.method==="POST"){
res.write('<html>');
res.write('<head><title> File fs.writeFileSync('user.txt',
Syatem</title></head>'); 'Coding Monk');
res.write('<body><h1> Write Data in res.statusCode=302;
file</h1>'); res.setHeader('Location','/');
res.write('<form return res.end();
action="/submit-details" method="post">') }
res.write('<input type="text" else{
name="username" placeholder="Enter your res.write('page not found');
name"><br>'); }
res.write('<label for ="male"> Male });
</lable>'); const PORT=3000;
res.write('<input type="radio" id="male" server.listen(PORT,()=>{
name="gender" value="male" />'); console.log('Server running on
res.write('<label for ="male"> Female address http://localhost:${port}')
</lable>'); });
res.write('<input type="radio"
File System in Node.js (fs Module)
Node.js provides a built-in File System (fs) module that allows us to interact
with the file system. It supports reading, writing, updating, deleting, and
renaming files.

Importing the fs Module


Before using any file operations, you need to import the fs module:

const fs = require('fs');
Reading a File in Node.js
The fs.readFile() method is used to read files asynchronously. It does not block the execution of
other code while reading the file.

const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {


if (err) {
console.log('Error reading file:', err);
} else {
console.log('File Content:', data);
}
});
fs.readFile('example.txt', 'utf8', callback) → Reads example.txt in UTF-8 format.

If there’s an error (e.g., file not found), it prints the error.

Otherwise, it prints the file content.


Writing to a File in Node.js
The fs.writeFile() method is used to write data to a file. If the file does not exist, it
creates one.

const fs = require('fs');

fs.writeFile('example.txt', 'Hello, this is a new file!', (err) => {


if (err) {
console.log('Error writing file:', err);
} else {
console.log('File written successfully!');
}
});

fs.writeFile('example.txt', 'Content', callback) → Creates or overwrites


example.txt with new content.

If an error occurs, it is logged. Otherwise, it prints "File written successfully!".


Appending Data to a File
The fs.appendFile() method is used to add new content without overwriting existing
data.

const fs = require('fs');

fs.appendFile('example.txt', '\nAppended Text!', (err) => {


if (err) {
console.log('Error appending file:', err);
} else {
console.log('Content appended successfully!');
}
})
fs.appendFile('example.txt', 'Content', callback) → Adds new content at
the end of the file.
This preserves the existing content.
Deleting a File in Node.js
The fs.unlink() method is used to delete a file from the system.

const fs = require('fs');

fs.unlink('example.txt', (err) => {


if (err) {
console.log('Error deleting file:', err);
} else {
console.log('File deleted successfully!');
}
});
fs.unlink('example.txt', callback) → Removes example.txt permanently.

If the file doesn’t exist, it throws an error.


Checking If a File Exists
Before reading, writing, or deleting, we can check if a file exists using
fs.existsSync().

const fs = require('fs');

if (fs.existsSync('example.txt')) {
console.log('File exists');
} else {
console.log('File does not exist');
}

fs.existsSync('example.txt') → Returns true if the file exists, otherwise


false.
Parsing Request
1. Streams
2. Chunks
3. Buffers
4. Reading Chunk
5. Buffering Chunks
6. Parsing Request
7. Using Modules
Streams
Streams
Chunks
Buffers

You might also like