nodejs how to send html
To send HTML using Node.js, you can follow these steps:
- Import the necessary modules:
- Require the 'http' module to create an HTTP server.
Require the 'fs' module to read the HTML file.
Create an HTTP server:
- Use the
createServer
method from the 'http' module to create an HTTP server. Pass a callback function as a parameter to handle incoming requests.
Read the HTML file:
- Use the
readFile
method from the 'fs' module to read the HTML file. - Pass the file path and a callback function as parameters.
In the callback function, handle any errors and store the HTML content in a variable.
Set the response headers:
- Use the
response.writeHead
method to set the 'Content-Type' header to 'text/html'. This informs the client that the response will contain HTML content.
Send the HTML content as the response:
- Use the
response.end
method to send the HTML content as the response. Pass the HTML content variable as a parameter.
Start the server:
- Use the
listen
method to start the server. - Pass the desired port number and an optional callback function to handle any errors.
Here's an example code snippet that demonstrates sending HTML using Node.js:
const http = require('http');
const fs = require('fs');
const server = http.createServer((request, response) => {
fs.readFile('path/to/file.html', (error, htmlContent) => {
if (error) {
response.writeHead(500);
response.end('Error reading HTML file');
} else {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(htmlContent);
}
});
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
Please note that you need to replace 'path/to/file.html'
with the actual path to your HTML file, and 'port 3000'
with the desired port number to run your server on.