1.
Display a message in the browser
Input:
const http = require('http');
const server = [Link]((req, res) => {
[Link](200, { 'Content-Type':
'text/html' });
const message = `
<html>
<head>
<title>[Link] Message</title>
</head>
<body style="display: flex; justify-content:
center; align-items: center; height: 100vh;
background-color: #222; color: white; text-align:
center;">
<div>
<h1 style="color: #4CAF50; font-size:
3em;">Hello Everyone</h1>
<p style="font-size: 1.5em;">This is
a message served by a [Link] server.</p>
</div>
</body>
</html>
`;
[Link](message);
});
[Link](3000, () => {
[Link]('Server running at
[Link]
});
Output:
[Link] the current date and time in the browser.
INPUT:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-
width, initial-scale=1.0">
<title>Live Digital Clock</title>
<style>
body {
background: linear-gradient(45deg,
#ec2654, #e6543a, #3894f0);
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
color: white;
text-align: center;
}
.clock {
font-size: 60px;
font-weight: bold;
background: rgba(0, 0, 0, 0.3);
padding: 20px 40px;
border-radius: 15px;
box-shadow: 0px 0px 15px rgba(0, 0, 0,
0.3);
}
</style>
</head>
<body>
<div class="clock" id="clock">[Link]</div>
<script>
function updateClock() {
const now = new Date();
let hours =
[Link]().toString().padStart(2, '0');
let minutes =
[Link]().toString().padStart(2, '0');
let seconds =
[Link]().toString().padStart(2, '0');
[Link]('clock').innerText = `$
{hours}:${minutes}:${seconds}`;
}
setInterval(updateClock, 1000);
updateClock(); // Initial call to prevent 1-
second delay
</script>
</body>
</html>
OUTPUT:
[Link] a query string in URL
INPUT:
const http = require('http');
const url = require('url');
const hostname = 'localhost';
const port = 8356;
const server = [Link]((req, res) => {
const parsedUrl = [Link]([Link], true);
const query = [Link];
[Link] = 200;
[Link]('Content-Type', 'text/html');
if ([Link] && [Link]) {
[Link](<h1>Hello, ${[Link]}!</h1><p>You are ${[Link]}
years old.</p>);
} else {
[Link](`<h1>Welcome!</h1><p>Pass a query string like this: <br>
<code>[Link]
});
[Link](port, hostname, () => {
[Link](🚀 Server running at [Link]
});
OUTPUT:
[Link] up a webpage address into readable parts
INPUT:
const url = require('url');
const webAddress =
'[Link]
name=john&age=30#section1';
const parsedUrl = new URL(webAddress);
[Link]('Protocol:', [Link]);
[Link]('Host:', [Link]);
[Link]('Hostname:', [Link]);
[Link]('Port:', [Link]);
[Link]('Pathname:', [Link]);
[Link]('Search Params:', [Link]);
[Link]('Hash:', [Link]);
const searchParams =
[Link]([Link]());
[Link]('Query Parameters:', searchParams);
OUTPUT:
Protocol: https:
Host: [Link]
Hostname: [Link]
Port: 8080
Pathname: /path/to/page
Search Params: ?name=john&age=30
Hash: #section1
Query Parameters: { name: 'john', age: '30' }
[Link] customized error message
INPUT:
class CustomError extends Error {
constructor(message, statusCode) {
super(message);
[Link] = "CustomError";
[Link] = statusCode;
}
}
try {
throw new CustomError("User not found", 404);
} catch (error) {
[Link](`Error: ${[Link]} (Status
Code: ${[Link]})`);
}
OUTPUT:
Error: User not found (Status Code: 404)
[Link] handling
INPUT:
const EventEmitter = require('events');
class OrderProcessor extends EventEmitter {
placeOrder(orderId, customerName) {
[Link](`📦 Order placed: ${orderId} by $
{customerName}`);
[Link]('orderReceived', orderId);
}
}
const orderProcessor = new OrderProcessor();
[Link]('orderReceived', (orderId) => {
[Link](`🔄 Processing order: ${orderId}...`);
setTimeout(() => {
[Link](`✅ Order ${orderId} is completed!
`);
}, 2000);
});
[Link](101, "Alice");
OUTPUT:
📦 Order placed: 101 by Alice
🔄 Processing order: 101...
✅ Order 101 is completed!
[Link]
[Link] of 2 middle wares
INPUT:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const port = 3000;
const requestLogger = (req, res, next) => {
[Link](`${[Link]} ${[Link]} - ${new
Date().toISOString()}`);
next();
};
const authMiddleware = (req, res, next) => {
const token = [Link]['authorization'];
if (token === 'secret-token') {
next();
} else {
[Link](403).json({ message: 'Forbidden: Invalid Token' });
}
};
[Link]([Link]());
[Link](requestLogger);
[Link](authMiddleware);
const apiRouter = [Link]();
[Link]('/data', (req, res) => {
[Link](200).json({ message: 'GET request received', data: [1,
2, 3] });
});
[Link]('/data', (req, res) => {
[Link](201).json({ message: 'POST request received',
receivedData: [Link] });
});
[Link]('/data/:id', (req, res) => {
[Link](200).json({ message: `PUT request received for ID $
{[Link]}`, updatedData: [Link] });
});
[Link]('/data/:id', (req, res) => {
[Link](204).send();
});
[Link]('/api', apiRouter);
[Link]([Link]([Link](__dirname, 'public')));
[Link]('/', (req, res) => {
[Link]([Link](__dirname, 'public', '[Link]'));
});
[Link](port, () => {
[Link](`Server running on [Link]
});
OUTPUT:
GET / - 2025-03-03T[Link].136Z
GET /[Link] - 2025-03-03T[Link].316Z
[Link] paths using URL prefix.
INPUT:
const express = require('express');
const app = express();
const PORT = 3000;
[Link]((req, res, next) => {
if ([Link]('/api')) {
return next();
}
[Link](403).send('Forbidden: Access restricted to API routes');
});
[Link]('/api/users', (req, res) => {
[Link]({ message: 'User list' });
});
[Link]('/api/products', (req, res) => {
[Link]({ message: 'Product list' });
});
[Link](PORT, () => {
[Link](`Server is running on [Link]
});
OUTPUT:
[Link] the status code.
Input:
const express = require('express');
const app = express();
// API route that returns JSON with a status code
[Link]('/api/message', (req, res) => {
[Link](200).json({ message: "Hello, this is an Express
API!" });
});
// Start the server
const PORT = 2000;
[Link](PORT, () => {
[Link](`Server is running on [Link]
});
OUTPUT:
{"message":"Hello, this is an Express
API!"}
[Link] data from request.
INPUT:
const express = require('express');
const app = express();
const PORT = 3000;
[Link]('/', (req, res) => {
[Link]('Welcome to my [Link] App!');
});
[Link](PORT, () => {
[Link](`Server is running on [Link]
});
OUTPUT:
[Link] GET,POST,PUT and DELETE requests.
INPUT:
const express = require('express');
const app = express();
const PORT = 3000;
[Link]([Link]());
[Link]('/', (req, res) => {
[Link]('Hello, welcome to my Express server!');
});
[Link]('/echo', (req, res) => {
[Link]({ message: 'You sent:', data: [Link] });
});
[Link](PORT, () => [Link](`🚀 Server running on
[Link]
OUTPUT:
6. Using middleware to log request details.
INPUT:
const express = require('express');
const app = express();
const requestLogger = (req, res, next) => {
const timeStamp = new Date().toISOString();
[Link](`[${timeStamp}] ${[Link]} ${[Link]}`);
next(); // Pass control to the next middleware
};
[Link](requestLogger);
[Link]('/', (req, res) => {
[Link]('Hello, World!');
});
[Link]('/about', (req, res) => {
[Link]('About Page');
});
const PORT = 3000;
[Link](PORT, () => {
[Link](`Server is running on [Link]
});
OUTPUT:
[Link] HTML,CSS AND JAVSCRIPT files.
INPUT:
const express = require('express');
const app = express();
// Route to serve the HTML page
[Link]('/', (req, res) => {
[Link](`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Express Inline Page</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f0f0f0;
padding: 50px;
h1 {
color: #333;
button {
background-color: #007bff;
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
border-radius: 5px;
button:hover {
background-color: #0056b3;
</style>
</head>
<body>
<h1>Welcome to Express Inline Page</h1>
<button onclick="showMessage()">Click Me</button>
<script>
function showMessage() {
alert("Hello from Express!");
</script>
</body>
</html>
`);
});
// Start the server
const PORT = 3000;
[Link](PORT, () => {
[Link](`Server is running on [Link]
});
OUTPUT:
[Link] JSON data from an API.
INPUT:
const express = require('express');
const app = express();
const users = [
{ id: 1, name: "Alice", email: "alice@[Link]" },
{ id: 2, name: "Bob", email: "bob@[Link]" },
{ id: 3, name: "Charlie", email: "charlie@[Link]" }
];
[Link]('/api/users', (req, res) => {
[Link](users);
});
const PORT = 5000;
[Link](PORT, () => {
[Link](`Server is running on [Link]
});
OUTPUT:
[{"id":1,"name":"Alice","email":"alice@[Link]"},
{"id":2,"name":"Bob","email":"bob@[Link]"},
{"id":3,"name":"Charlie","email":"charlie@[Link]"}]