Explanation of how to use the http.response.end method in Node.js.
In Node.js, the method http.response.end() is used to terminate an HTTP response. It can take an optional parameter to send as the response body to the client.
The general format for using the http.response.end() method is as follows:
response.end([data][, encoding][, callback])
Explanation of parameters:
- Data (optional): The response body data to be sent to the client. It can be a string, a Buffer object, or a readable stream. If this parameter is not provided, the response body will be empty.
- Encoding (optional): If the data parameter is a string, you can specify its encoding, which defaults to utf-8.
- Optional callback: A function that can be called after the response has ended.
Example of use:
- Send a simple response body.
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello, World!');
});
server.listen(3000);
- Send response body using Buffer object.
const http = require('http');
const server = http.createServer((req, res) => {
const data = Buffer.from('Hello, World!', 'utf-8');
res.end(data);
});
server.listen(3000);
- Send the response body using a readable stream.
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
const readableStream = fs.createReadStream('file.txt');
res.end(readableStream);
});
server.listen(3000);
Points to note:
- The method http.response.end() can only be called once in the response handling function; calling it multiple times will result in an exception.