render html in node js
// Step 1: Import required modules
const http = require('http');
const fs = require('fs');
// Step 2: Create an HTTP server
const server = http.createServer((req, res) => {
// Step 3: Check if the request URL is for the root path '/'
if (req.url === '/') {
// Step 4: Read the HTML file content
fs.readFile('index.html', 'utf8', (err, data) => {
// Step 5: Check for errors while reading the file
if (err) {
// Step 6: Handle the error and send an HTTP 500 response
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Internal Server Error');
} else {
// Step 7: Send an HTTP 200 response with the HTML content
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
}
});
} else {
// Step 8: Send an HTTP 404 response for any other path
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not Found');
}
});
// Step 9: Set the server to listen on port 3000
server.listen(3000, '127.0.0.1', () => {
console.log('Server listening on port 3000');
});
This Node.js script creates a simple HTTP server that serves an HTML file when the root path '/' is requested. The script follows these steps:
- Import the required modules (
http
for creating an HTTP server andfs
for reading files). - Create an HTTP server using
http.createServer
. - Check if the request URL is for the root path ('/').
- Read the content of the 'index.html' file using
fs.readFile
. - Check for errors while reading the file.
- If an error occurs, handle it and send an HTTP 500 response.
- If there are no errors, send an HTTP 200 response with the HTML content.
- For any path other than '/', send an HTTP 404 response.
- Set the server to listen on port 3000 and log a message when it starts.