Node.js http.ServerResponse.end() Method
Last Updated :
05 Apr, 2023
The httpServerResponse.end() is an inbuilt application programming interface of class Server Response within http module which is used to send the signal to the server that all the header has been sent.
Syntax:
response.end(data, Encodingtype, Callbackfunction)
Parameters: This method takes three Parameters
- Data: Chunk of data that has to be sent
- Encoding Type: Type encoding for the data
- Callback: Callback function for further operation if necessary.
Return Value: This method returns this Server Response object.
Example 1: Filename: index.js
Javascript
const http = require( 'http' );
const PORT = process.env.PORT || 3000;
const httpServer = http.createServer(
function (request, response) {
const value = response.connection;
response.end( "port address : " +
value.address().port, 'utf8' , () => {
console.log( "displaying the result..." );
httpServer.close(() => {
console.log( "server is closed" )
})
});
});
httpServer.listen(PORT, () => {
console.log( "Server is running at port 3000..." );
});
|
Steps to run:
node index.js
Console output:
Server is running at port 3000...
displaying the result...
displaying the result...
server is closed
server is closed
Browser Output: Paste the localhost address http://localhost:3000/. In the search bar of the browser.
port address : 3000
Example 2: Filename: index.js
Javascript
const http = require( 'http' );
const http2Handlers = (request, response) => {
const value = response.connection;
response.end( "family : " +
value.address().family, 'utf8' , () => {
console.log( "displaying the result..." );
httpServer.close(() => {
console.log( "server is closed" )
})
});
};
const httpServer = http.createServer(
http2Handlers).listen(3000, () => {
console.log( "Server is running at port 3000..." );
});
|
Steps to run:
node index.js
Console output:
Server is running at port 3000...
displaying the result...
displaying the result...
server is closed
server is closed
Browser Output: Paste the localhost address http://localhost:3000/. In the search bar of the browser.
family : IPv6
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_response_end_data_encoding_callback
Share your thoughts in the comments
Please Login to comment...