FSD Unit04 (Ques)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

FSD

UNIT - 4
Syllabus : Basics of Node.js HTTP, Creating simple webs server, Inspecting headers, Request
and response, Serving base HTML, Serving a directory, Middleware, Create and use
middleware, HTTPs module.

 Basics of Node.js HTTP:


 The Built-in HTTP Module: Node.js has a built-in module called HTTP,
which allows Node.js to transfer data over the Hyper Text Transfer
Protocol (HTTP). To include the HTTP module, use the require() method:
var http = require('http');
 Methods of Node.js :
(1) http.createServer()- Return a new instance of the http.Server class.
(2) http.request() - Makes an HTTP request to a server, creating an instance
of the http.ClientRequest class.
(3) http.get()- Similar to http.request(), but automatically sets the HTTP
method to GET &calls req.end() automatically.
 Node.js as a Web Server
The HTTP module can create an HTTP server that listens to server ports and
gives a response back to the client. Use the createServer() method to create an
HTTP server:

var http = require('http'); //create a server object:


http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

Output:
FSD

 var http = require('http');- Imports the built-in http module, providing


Node.js with HTTP functionality.
 http.createServer(function (req, res) { ... });: Creates an HTTP server
using http.createServer(). The callback function handles incoming
requests:
(a) req: An object representing the incoming request, containing details like
method (GET,….).
(b) res: An object used to send a response to the client, including methods for
setting headers, writing data, and ending the response.
 console.log(req.method, req.url);: Logs the client's request method and
URL for debugging or understanding user behavior.
 res.write('Hello!');: Writes the string "Hello!" to the response body, which
will be sent to the client when the response is ended.
 res.end();: Marks the end of the response, sends all buffered data to the
client, and closes the connection.
 server.listen(8080);: Starts the server listening on port 8080. This makes
the server accessible to clients at http://localhost:8080/.
 console.log('Server listening on port 8080');: Logs a message to the
console indicating the server is ready.

 Request and response:

 User initiates a request: The user specifies a file name or directory and
the desired action (e.g., read, write, delete).
 Request sent to file server: The request is sent to the file server.
 File server interacts with file system: The file server queries the file
system based on the user's request. This might involve locating the file,
checking permissions, and preparing the data.
 Response sent to user: The file server sends a response back to the user,
indicating success or failure and providing any necessary data (e.g., the
contents of a file).
FSD

const http = require('http'); // Import the http module

// Create an HTTP server with proper error handling


const server = http.createServer((req, res) => {
try {
// Set the response status code to 200 (OK)
res.statusCode = 200;
// Set the response content type to plain text
res.setHeader('Content-Type', 'text/plain');
// End the response with the message "An illustration to request & response !"
res.end('An illustration to request & response !\n');
} catch (error) {
console.error('Error occurred:', error);
res.statusCode = 500; // Set appropriate error status code
res.end('Internal Server Error'); // Provide user-friendly error message
}
});

// Start listening for incoming requests on port 8080 with error handling
server.listen(8080, (err) => {
if (err) {
console.error('Error starting server:', err);
// handle the error appropriately, e.g., exit process
FSD

} else {
console.log('An illustration to request & response !');
}
});

Output:

Streams: Both requests and responses in Node.js are represented as streams.


This means they have events like data, end, and error that you can listen to in
order to process the data as it arrives.
There are different types of streams, such as:
(A)Readable streams: Used for reading data (e.g., file read streams,
incoming HTTP requests).
(B) Writable streams: Used for writing data (e.g., file write streams, outgoing
HTTP responses).
(C) Duplex streams: Can both read and write data (e.g., TCP sockets).
Pipes: The pipe() method is used to connect two streams, allowing data to flow
from one to the other automatically. This is particularly useful when you want
to:
(A)Process or transform data on the fly: You can chain multiple streams
together, with each performing specific operations on the data.
(B) Send a response before it's completely generated: Instead of buffering the
entire response in memory, you can start sending it to the client as soon
as you have some data available.
Example: Streaming a File
const fs = require('fs');

const readableStream = fs.createReadStream('your_file.txt');


const writableStream = fs.createWriteStream('output.txt');

readableStream.pipe(writableStream);

readableStream.on('end', () => {
FSD

console.log('File streamed successfully!');


});

readableStream.on('error', (err) => {


console.error('Error reading file:', err);
});
Code Explanation:
 Import the fs module for file system operations.
 Create readable and writable streams for the input and output files.
 Connect the streams using pipe(): data from readableStream flows
directly to writableStream.
 Add event listeners:
'end': Log a message when the file is fully streamed.
'error': Handle potential errors gracefully.
Output:
The contents of your_file.txt will be written to output.txt, without loading
the entire file into memory at once.
You'll see "File streamed successfully!" in the console after completion.

 Http Module in Node.js:


The http module in Node.js is a built-in module that allows you to create HTTP
servers and clients. It provides an easy way to create and handle HTTP requests
and responses.
The http module provides two main classes: http.Server for creating HTTP
servers, and http.ClientRequest for making HTTP requests.

Here's an example of an HTTP server using the http module:


const http = require('http');

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


try {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
} catch (error) {
console.error('Error occurred:', error);
FSD

res.statusCode = 500;
res.end('Internal Server Error');
}
});
server.listen(8080, () => {
console.log('To understand http modules ');
});
Output:
FSD

Q-2: Serving based html and serving directory?

http
const http = require('http');

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

res.statusCode = 200;

res.setHeader('Content-Type', 'text/html');

res.end('<html><body><h1>Hello, World!</h1></body></html>');

});

server.listen(3000,'127.0.0.1',()=>{

console.log('server running at http://127.0.0.1:3000/');

});

We first require the http module, which comes built-in with Node.js.

We define the hostname and port where our server will listen for incoming requests. In this case, we're
using localhost (127.0.0.1) and port 3000.

We create an HTTP server using the http.createServer() method and pass in a request listener function.
This function will be called every time the server receives a request.

In the request listener function, we first set the HTTP status code to 200.

We then set the Content-Type header to text/html to indicate that we will be sending HTML content.

Finally, we end the response by sending the HTML content, which in this case is a simple <h1> heading
that says "Hello, World!".

We start the server by calling the server.listen() method and pass in the hostname and port that we
defined earlier.

When the server is running, we log a message to the console indicating that it is up and running.

To run the server, save the code to a file (e.g. server.js) and run it using the node command:
FSD

You should see the message "Server running at http://127.0.0.1:3000/" in the console.

To test the server, open a web browser and navigate to the URL "http://127.0.0.1:3000". You should
see the "Hello, World!" heading displayed in the browser.

Directory

Here is a basic example of serving a directory using Node.js and the http and fs (file system) modules
FSD

const http = require('http');

const fs = require('fs');

const path = require('path');

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

const filePath = '.' + req.url;

if (filePath === './') {

filePath = './index.html';

fs.readFile(filePath, (err, data) => {

if (err) {

res.statusCode = 404;

res.setHeader('Content-Type', 'text/html');

res.end('<html><body><h1>Error 404: File not


found</h1></body></html>');

} else {

res.statusCode = 200;

res.setHeader('Content-Type', 'text/html');

res.end(data);

});

});

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

console.log('server running at http://127.0.0.1:8000/');

});
FSD

Mime

MIME stands for Multipurpose Internet Mail Extensions.


It is a fundamental part of communication protocols such as HTTP.
The MIME type is required when you need to transfer non-text data.
MIME was originally designed to extend the capabilities of email to support more data types
such as non-ASCII text files and binary files such as images, PDFs, and executables.
The use of MIME is not limited to email. It is now actively used in all communications over
the Internet to describe the type of data sent to or from a server.
It is often referred to as a media type or MIME content type.
In HTTP, the MIME-type is part of the Content-Type header of an HTTP message and defines
the data type in the body of an HTTP request or response.
Setting the correct MIME data type in the body of the message is critical for both HTTP
requests and responses and allows you to control how the request is interpreted by the client
and server.
Web servers and browsers have a list of well-known file extensions and MIME types. This
helps them identify and interpret all known file types, regardless of the operating system and
hardware used by the user.

const mime = require('mime');

// Example file paths

const filePaths = [

'index.html',

'style.css',

'script.js',

'image.png',

'document.pdf'

];

// Determine MIME type for each file

filePaths.forEach(filePath => {

const mimeType = mime.getType(filePath);


FSD

console.log(`File: ${filePath}, MIME type: ${mimeType}`);

});

Mimelookup
var http = require('http');
var path = require('path');
var fs = require('fs');
var mimelookup={'.js':'application/js','.html':'text/html'};
var server=http.createServer(function(req,res){
if(req.method=='GET'){
var fileurl;
if(req.url=='/')fileurl='/index.html';
else
fileurl=req.url;
var filepath=path.resolve('./public'+fileurl);
var fileExt=path.extname(filepath);
var mimeType=mimelookup[fileExt];
if(!mimeType){
send404(res);
return;
}
fs.exists (filepath,function(exists){
FSD

if(!exists){
send404(res);
return;
};
res.writeHead(200,{'content-Type':mimeType});
fs.createReadStream (filepath).pipe(res);
});
}
else{
send404(res);
}
});
server.listen(8000,'127.0.0.1',()=>{
console.log('server running at http://127.0.0.1:8000/');
});
FSD

Q-3 Inspecting Headers in Node.js:


Imagine you're building a Node.js web server and want to understand what information your users
are sending through their requests. This information often hides within headers, small pieces of data
attached to each request carrying details like browser type, location, or authorization tokens.
Inspecting these headers can be crucial for understanding user behavior, debugging issues, and
ensuring security.

Here's how you can inspect a header in Node.js


Using the http Module (General Approach):

Example :
const http = require('http');

// Create an HTTP server

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

const headers = req.headers; // Access headers on the IncomingMessage object

// Iterate over all headers for detailed inspection

for (const header in headers) {

console.log(`${header}: ${headers[header]}`);

res.end(); // Respond to the request

});

// Start the server and listen for connections

server.listen(3000, () => {

console.log("Server listening on port 3000");

});

Output:

You might also like