0% found this document useful (0 votes)
8 views22 pages

WD Unit 4

This document covers the basics of setting up a Node.js environment, creating a basic server, and handling HTTP requests and responses. It introduces Express.js for building web applications and discusses middleware, asynchronous JavaScript with callbacks and promises, and file system operations. The content is structured into lectures that progressively build on web development concepts using Node.js and Express.js.

Uploaded by

abhi9897sharmag
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)
8 views22 pages

WD Unit 4

This document covers the basics of setting up a Node.js environment, creating a basic server, and handling HTTP requests and responses. It introduces Express.js for building web applications and discusses middleware, asynchronous JavaScript with callbacks and promises, and file system operations. The content is structured into lectures that progressively build on web development concepts using Node.js and Express.js.

Uploaded by

abhi9897sharmag
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

Notes

Web Development
Unit 4
Lecture 1: Setting Up a [Link] Environment & Creating a
Basic Server
1. What is [Link]?
 Runtime Environment: It's not a language or a
framework. It's a runtime that allows you to execute
JavaScript code outside of a web browser.
 Built on Chrome's V8: Uses the powerful V8 JavaScript
engine.
 Single-Threaded, Event-Driven: Uses an event loop to
handle asynchronous operations efficiently, making it
great for I/O-intensive tasks.
2. Setting Up the Environment
1. Download & Install:
o Go to [Link].
o Download the LTS (Long Term Support) version for
stability.
o Run the installer and follow the steps.
2. Verify Installation:
o Open your terminal/command prompt.
o Check the versions:
node --version
npm --version
3. The [Link] File
 The manifest file for your [Link] project.
 Tracks dependencies, scripts, and project metadata.
 Create one with: npm init or npm init -y (for default
settings).
4. Creating a Basic HTTP Server
 [Link] has a built-in http module to create servers.
Code Example for: [Link]
// 1. Import the built-in 'http' module
const http = require('http');
// 2. Define the port our server will run on
const port = 3000;
// 3. Create the server using the [Link]() method
// The callback function handles incoming requests (req) and
sends responses (res)
const server = [Link]((req, res) => {
// Set the response header with a 200 OK status and
content type
[Link](200, { 'Content-Type': 'text/plain' });
// Send the response body
[Link]('Hello World from my first [Link] server!\n');
});

// 4. Tell the server to start listening on the specified port


[Link](port, () => {
[Link](`Server is running and listening on
[Link]
});
5. Running the Server
 In the terminal, run: node [Link]
 Open your browser and go to [Link]

Lecture 2: Handling HTTP Requests and Responses in


[Link]
1. The Request (req) Object
 Contains information about the incoming client request.
 Key Properties:
o [Link]: The path/URL of the request
(e.g., /, /about).
o [Link]: The HTTP method (GET, POST, PUT,
DELETE).
o [Link]: An object containing the request
headers.
2. The Response (res) Object
 Used to construct and send a response back to the
client.
 Key Methods:
o [Link](statusCode, headers): Sends
response headers.
o [Link](data): Writes data to the response body.
o [Link]([data]): Signals that the response is
complete. Optional data can be sent.
3. Basic Routing
 Check the [Link] and [Link] to decide how to
respond.
Code Example for: Basic Routing
const http = require('http');
const server = [Link]((req, res) => {
const url = [Link];
const method = [Link];
// Home Page Route
if (url === '/' && method === 'GET') {
[Link](200, { 'Content-Type': 'text/html' });
[Link]('<h1>Home Page</h1>');
}
// About Page Route
else if (url === '/about' && method === 'GET') {
[Link](200, { 'Content-Type': 'text/html' });
[Link]('<h1>About Us</h1>');
}
// Handle 404 - Not Found
else {
[Link](404, { 'Content-Type': 'text/html' });
[Link]('<h1>Page Not Found</h1>');
}
});
[Link](3000);
4. Parsing Request Body (for POST requests)
 Data from forms (POST) is sent in chunks. You need to
collect it.
Code Example for: Handling POST Data
const http = require('http');
const server = [Link]((req, res) => {
if ([Link] === '/message' && [Link] === 'POST') {
const body = []; // Array to collect data chunks

// 'data' event is emitted when a new chunk of data is


received
[Link]('data', (chunk) => {
[Link](chunk);
});

// 'end' event is emitted when all data has been received


return [Link]('end', () => {
const parsedBody = [Link](body).toString(); //
Combine chunks
[Link](parsedBody); // e.g., message=Hello+World
[Link](200, { 'Content-Type': 'text/plain' });
[Link]('Message received!');
});
}
// ... other routes
});
Lecture 3: Introduction to [Link] and Setting Up Routes
1. What is [Link]?
 A minimal, flexible, and unopinionated web
framework for [Link].
 It simplifies the process of building web applications and
APIs by providing a robust set of features.
 It sits on top of [Link]'s built-in http module,
abstracting away complexity.
2. Setting Up an Express Project
1. Create a new project directory: mkdir my-express-app
2. Initialize [Link]: npm init -y
3. Install Express: npm install express
3. Creating a Basic Express Server
Code Example for: [Link]
// 1. Import Express
const express = require('express');
// 2. Create an Express application
const app = express();
// 3. Define the port
const PORT = 3000;
// 4. Define a basic route for the home page
// [Link](PATH, HANDLER)
[Link]('/', (req, res) => {
[Link]('<h1>Hello from Express!</h1>');
});

// 5. Start the server


[Link](PORT, () => {
[Link](`Express server listening on port ${PORT}`);
});
4. Routing in Express
 Routing refers to how an application's endpoints (URIs)
respond to client requests.
 Structure: [Link](PATH, HANDLER_FUNCTION)
 METHOD: HTTP method
(e.g., [Link], [Link], [Link], [Link]).
 PATH: The path on the server.
 HANDLER: The function executed when the route is
matched.
Code Example: More Routes
javascript
[Link]('/', (req, res) => {
[Link]('Home Page - GET');
});
[Link]('/users', (req, res) => {
[Link]('List of users');
});
[Link]('/users', (req, res) => {
// Code to create a new user
[Link]('User created!');
});
// Route Parameters - dynamic segments of the URL
[Link]('/users/:userId', (req, res) => {
const userId = [Link]; // Access the parameter
[Link](`Viewing profile of user ${userId}`);
});
Lecture 4: Working with Express Middleware and Request
Handling
1. What is Middleware?
 Functions that have access to the request object (req),
the response object (res), and the next function in the
application’s request-response cycle.
 Middleware can:
o Execute any code.
o Make changes to the request and response objects.
o End the request-response cycle.
o Call the next middleware in the stack.
2. The next() Function
 When called, it passes control to the next middleware
function in the stack.
 If next() is not called, the request will be left hanging.
3. Using Built-in and Third-Party Middleware
 [Link](): Parses incoming requests with JSON
payloads. (Built-in)
 [Link](): Parses incoming requests with
URL-encoded payloads. (Built-in)
 morgan: Logs HTTP requests. (Third-party) - Install
with npm install morgan
Code Example for: Using Essential Middleware
const express = require('express');
const morgan = require('morgan');
// Import third-party middleware
const app = express();
// Use Morgan for logging ('dev' is a predefined format)
[Link](morgan('dev'));
// Parse JSON bodies (for requests with Content-Type:
application/json)
[Link]([Link]());
// Parse URL-encoded bodies (for form submissions)
[Link]([Link]({ extended: true }));
// Custom middleware function
[Link]((req, res, next) => {
[Link]('Time:', [Link]());
next(); // You MUST call next() to move on!
});
[Link]('/api/users', (req, res) => {
// [Link] now contains the parsed JSON or form data
[Link]([Link]);
[Link]({ message: 'User data received!', data: [Link] });
});
4. Order of Middleware Matters!
 Middleware are executed in the order they are defined
using [Link]().
Lecture 5: Understanding Asynchronous JavaScript:
Callbacks and Promises
1. The Problem: Blocking vs. Non-Blocking Code
 Synchronous (Blocking): Code executes line by line. Each
operation must finish before the next one starts. This
can make your application unresponsive.
 Asynchronous (Non-Blocking): Code can initiate an
operation and then move on to the next one before the
first finishes. The result is handled later. This is the core
of [Link].
2. Callbacks: The Original Pattern
 A callback is a function passed as an argument to
another function, to be executed later.
 [Link] Convention: "Error-first callbacks" – the first
parameter of the callback is reserved for an error object.
Code Example for: Callback Pattern
const fs = require('fs'); // File System module
// Synchronous (Blocking) - AVOID in server code!
const data = [Link]('./[Link]', 'utf8');
[Link](data);
// Asynchronous (Non-Blocking) - PREFERRED
[Link]('./[Link]', 'utf8', (err, data) => {
if (err) {
// Handle the error first!
[Link]('Error reading file:', err);
return;
}
// If no error, handle the data
[Link](data);
});
[Link]("This will run BEFORE the file is finished
reading!");
3. The Drawback: "Callback Hell"
 Nesting multiple asynchronous operations leads to
deeply nested, hard-to-read code.
javascript
doTask1((err, result1) => {
if (err) handleError(err);
doTask2(result1, (err, result2) => {
if (err) handleError(err);
doTask3(result2, (err, result3) => {
if (err) handleError(err);
// ... and so on
});
});
});
4. Promises: A Better Solution
 A Promise is an object representing the eventual
completion (or failure) of an asynchronous operation.
 It has 3 states: pending, fulfilled, rejected.
 It provides methods like .then() and .catch() for cleaner
chaining.
Code Example: Promise-based [Link] API
javascript
const fs = require('fs').promises; // Use the promises version

[Link]('./[Link]', 'utf8')
.then((data) => {
[Link]('File content (Promise):', data);
// Return another promise to chain
return [Link]('./[Link]', 'utf8');
})
.then((anotherData) => {
[Link]('Another file:', anotherData);
})
.catch((err) => {
// A single .catch() for any error in the chain
[Link]('An error occurred in the chain:', err);
});
Lecture 6: Using Async/Await for Cleaner Asynchronous
Code
1. What is Async/Await?
 Syntactic sugar built on top of Promises.
 It allows you to write asynchronous code that looks and
behaves like synchronous code.
 async: A keyword placed before a function to declare it
as asynchronous. This function always returns a
Promise.
 await: A keyword that can only be used inside
an async function. It pauses the execution of the async
function until a Promise is settled (fulfilled or rejected).
2. Basic Usage
Code Example for : Rewriting the Promise chain with
Async/Await
const fs = require('fs').promises;
// Define an async function
const readFiles = async () => {
try {
// Wait for this promise to resolve
const data = await [Link]('./[Link]', 'utf8');
[Link]('File content (Async/Await):', data);
// Then wait for this one
const anotherData = await [Link]('./[Link]',
'utf8');
[Link]('Another file:', anotherData);

} catch (err) {
// Use a standard try...catch block for error handling
[Link]('An error occurred:', err);
}
};

// Call the async function


readFiles();
3. Error Handling
 Use try...catch blocks to handle errors
in async functions. It's much cleaner than .catch().
4. Await in Parallel for Performance
 If operations don't depend on each other, you can run
them in parallel using [Link]().
Code Example for: Parallel Execution
const readFilesInParallel = async () => {
try {
// Start both file reads simultaneously
const [data1, data2] = await [Link]([
[Link]('./[Link]', 'utf8'),
[Link]('./[Link]', 'utf8')
]);
[Link]('File 1:', data1);
[Link]('File 2:', data2);
} catch (err) {
[Link]('One of the reads failed:', err);
}
};
Lecture 7: Working with the File System: Reading, Writing,
and Managing Files
1. The fs Module
 [Link] provides the fs module to interact with the file
system.
 It has both synchronous and asynchronous (callback-
based and promise-based) methods.
2. Core Methods
 Reading
Files: [Link](), [Link](), [Link]
()
 Writing
Files: [Link](), [Link](), [Link]
le()
o Note: writeFile overwrites the file if it exists.
Use appendFile to add content.
 Deleting Files: [Link](), [Link]()
 Getting File Info: [Link](), [Link]()
3. Code Examples with [Link]
const fs = require('fs').promises;
const fileOperations = async () => {
try {
// 1. Write to a file (creates it if it doesn't exist)
await [Link]('./[Link]', 'This is the initial
content.\n');
[Link]('File was written successfully.');

// 2. Read from the file


const content = await [Link]('./[Link]', 'utf8');
[Link]('File content after write:', content);
// 3. Append to the file
await [Link]('./[Link]', 'This is appended
content.\n');
[Link]('Content was appended.');

// 4. Read again to see the change


const updatedContent = await [Link]('./[Link]',
'utf8');
[Link]('File content after append:', updatedContent);

// 5. Get file information (stats)


const stats = await [Link]('./[Link]');
[Link]('File size:', [Link], 'bytes');
[Link]('Is it a file?', [Link]());

// 6. Delete the file


// await [Link]('./[Link]');
// [Link]('File was deleted.');

} catch (err) {
[Link]('File operation error:', err);
}
};

fileOperations();
Lecture 8: Advanced File Operations & Other [Link] I/O
Tasks
1. Working with Directories
 Create Directory: [Link](), [Link]()
 Read Directory: [Link](), [Link]() (lists
contents)
 Remove Directory: [Link](), [Link]() (only
works on empty dirs)
Code Example for: Directory Operations
const fs = require('fs').promises;
const dirOperations = async () => {
try {
// Create a new directory
await [Link]('./my-new-folder', { recursive: true }); //
recursive: true creates parent dirs if needed
[Link]('Directory created.');
// Read the contents of the current directory
const items = await [Link]('./');
[Link]('Contents of current directory:', items);
// Remove the directory (must be empty)
// await [Link]('./my-new-folder');
} catch (err) {
[Link]('Directory operation error:', err);
}
};
dirOperations();
2. Streams for Large Files
 Problem: readFile loads the ENTIRE file into memory.
For large files (videos, logs), this is inefficient.
 Solution: Streams
o Streams process data piece by piece (in chunks).
o They are memory efficient and faster for large data.
Code Example for: Copying a File with Streams
const fs = require('fs');
// Create readable and writable streams
const readStream = [Link]('./large-
video.mp4');
const writeStream = [Link]('./copy-large-
video.mp4');
// Pipe the read stream directly to the write stream
// This handles backpressure automatically
[Link](writeStream);
// Listen for events on the streams
[Link]('end', () => {
[Link]('File read finished.');
});
[Link]('finish', () => {
[Link]('File write finished.');
});
[Link]('error', (err) => {
[Link]('Write error:', err);
});
3. Other Core I/O Tasks
 path module: Provides utilities for working with file and
directory paths. Crucial for cross-platform compatibility.
const path = require('path');
const fullPath = [Link](__dirname, 'my-folder', '[Link]');
[Link](fullPath); // e.g., /home/user/project/my-
folder/[Link]
const ext = [Link](fullPath);
[Link](ext); // .txt
 Buffer: A global object used to handle binary data
directly (e.g., images, network packets).
 events module: [Link] core is built on an event-driven
architecture. You can create your own event emitters.

You might also like