Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
The Node.js HTTP module is a fundamental component for building web applications and services using Node.js. It provides a set of powerful tools and functions that enable developers to create HTTP servers and handle requests and responses efficiently. With the HTTP module, you can easily set up a server, define routes, process incoming data, and send responses back to clients.
Command to Include Node.js HTTP Module
Node.js HTTP module can be included using the following command:
const http = require('http')
Node.js HTTP Module Properties
Let us discuss the properties of the Node.js HTTP module:
1. http.METHODS
This is the property that lists all the HTTP methods.
It maintains a queue of pending requests for each host and port. It reuses the same socket until the queue is empty.
Node.js HTTP Module Methods
Let us talk about the methods of the Node.js HTTP module:
Method
Description
http.createServer()
Creates a new HTTP server instance.
server.listen()
Binds and listens for connections on the specified host and port.
server.close()
Stops the server from accepting new connections and closes existing connections.
server.setTimeout()
Sets the timeout value for sockets, controlling how long the server should wait for the next request.
request.on()
Attaches event listeners to the request object to handle events such as data, end, and error.
response.writeHead()
Sends a response header to the request, including the status code and headers.
response.write()
Sends a chunk of the response body. This method can be called multiple times to send multiple chunks of the response.
response.end()
Signals to the server that all response headers and body have been sent, ending the response process.
response.setHeader()
Sets a single header value for the response.
response.getHeader()
Retrieves the value of a single response header.
response.removeHeader()
Removes a header from the response.
response.statusCode
Sets or retrieves the HTTP status code of the response.
http.request()
Makes an HTTP request to a specified URL.
http.get()
Sends a GET request to a specified URL and returns a response.
Node.js HTTP Module Classes
Let us talk about the classes of the Node.js HTTP module:
1. HTTP.Agent
It manages connection persistence and reuses for HTTP clients. It does this by storing the pending requests in a queue and reusing a single socket connection until the queue is empty. It also maintains a pool of sockets to improve performance.
The http.globalAgent points to the global instance of the Agent object, which is an instance of the http.Agent class.
2. http.ClientRequest
It is created when HTTP.request() or HTTP.get() is called. After receiving the response, the response event is called with the response, with HTTP.IncomingMessage as arguments.
There are two ways to read the returned data:
Calling the response.read() method.
In the response event handler, an event listener can be set up for the data event so that the user can listen for the data streamed into.
3. HTTP.Server
This class is generally created as an instance while creating a new server using HTTP.createServer().
Methods of server object:
listen(): which is used for starting HTTP server and accepting responses.
close(): which is used for stopping the server from accepting responses.
4. http.ServerResponse
It is created by the http.Server and passed as a second argument to the request function.
Example:
const server = http.createServer((req, res) => {
// Here res is an http.ServerResponse object
})
Some ServerResponse methods and properties:
Methods
Properties
addTrailers()
adding HTTP trailing headers
end()
Signaling the server that the response is complete
finished
Returning true for complete response, otherwise false.
getHeader()
Returning specified header value
headersSent
Returning true if headers were the sent, otherwise false,
removeHeader()
Removes the specified header
setHeader()
Setting the specified header
setTimeout
Setting the timeout value of the socket to the specified number of milliseconds
statusMessage
Sets the status message that will be sent to the client
write()
Sends text, or a text stream, to the client
writeContinue()
Sends a HTTP Continue message to the client
writeHead()
It sends status and response headers to the clients.
sendDate
It is set to true by default. Users can set it to false if the date header is not to be included in the response.
statusCode
It sets the status code that is to be sent to the client.
5. http.IncomingMessage
It represents the request to the server.
http.IncomingMessage object can be created by:
http.Server when listening to the request event
http.ClientRequest when listening to the response event
Some IncomingMessage methods and properties:
Methods
Properties
headers
It returns a key-value pair object containing header names and values.
rawHeaders
Returns array of request headers
httpVersion
Specifies HTTP version sent by the client.
setTimeout()
We can specify the time limit after we want to call a specific function.
statusCode
Tells the HTTP response status code
URL
Returns request URL string
trailers
Returns object containing the trailer
method
Returns request method
socket
Returns socket object for connection
rawTrailers
Returns array of raw request trailer keys and values
Frequently Asked Questions:
What is HTTP server module?
The HTTP server module in Node.js allows developers to create and manage web servers. It provides functionalities to handle HTTP requests and responses, enabling the development of web applications and services.
How to start an HTTP server with HTTP module?
To start an HTTP server with the HTTP module, use http.createServer() to create the server and server.listen() to bind it to a specific port, allowing it to listen for incoming requests.
What is HTTP in JavaScript?
HTTP in JavaScript refers to the protocol used for communication between clients and servers over the web. JavaScript can handle HTTP requests and responses, enabling web applications to interact with web servers.
Why is request response used in HTTP module?
The request-response model in the HTTP module is used to manage the interaction between clients and servers. It allows servers to process client requests, perform necessary actions, and send appropriate responses back to clients.
Conclusion
In this blog, we discussed the Node.js HTTP module. This module is a powerful tool for building and managing web servers and applications. By providing essential methods and functionalities for handling HTTP requests and responses, it simplifies the process of creating robust and scalable web solutions.