How can I redirect users to a 404.html page in a Node.js server?

Basic Node.js HTTP Server with 404 Redirect :

const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  // Define valid routes here
  const validRoutes = ['/home', '/about']; 

  // Check if the request URL matches any valid routes
  if (!validRoutes.includes(req.url)) {
    // If not, serve the 404.html page
    const filePath = path.join(__dirname, '404.html');
    fs.readFile(filePath, (err, data) => {
      if (err) {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('Error loading 404 page.');
      } else {
        res.writeHead(404, { 'Content-Type': 'text/html' });
        res.end(data);
      }
    });
  } else {
    // Handle valid routes
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Valid route!');
  }
});

server.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});