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:

  1. Import the required modules (http for creating an HTTP server and fs for reading files).
  2. Create an HTTP server using http.createServer.
  3. Check if the request URL is for the root path ('/').
  4. Read the content of the 'index.html' file using fs.readFile.
  5. Check for errors while reading the file.
  6. If an error occurs, handle it and send an HTTP 500 response.
  7. If there are no errors, send an HTTP 200 response with the HTML content.
  8. For any path other than '/', send an HTTP 404 response.
  9. Set the server to listen on port 3000 and log a message when it starts.