Serve 404 for Undefined Routes :
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
const validRoutes = ['/home', '/about'];
if (validRoutes.indexOf(req.url) === -1) {
// Send 404 response and serve 404.html if route doesn't exist
fs.readFile(path.join(__dirname, '404.html'), (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('500 Server Error');
} else {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end(data);
}
});
} else {
// Serve your valid route content here
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('This is a valid route');
}
});
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});