1. Create a simple HTTP server that responds with "Hello, World!" for all requests.
2. const http = require('http');
3.
4. const PORT = 3000;
5.
6. // Create the server
7. const server = [Link]((req, res) => {
8. [Link](200, { 'Content-Type': 'text/plain' });
9. [Link]('Hello, World!\n');
10. });
11.
12. // Start the server
13. [Link](PORT, () => {
14. [Link](`Server running at [Link]
{PORT}/`);
15. });
16.
[Link] a server and upload a file to the server via a HTML file, and the server saves the
uploaded file to the server's filesystem.
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const PORT = 3000;
// Configure storage for uploaded files
const storage = [Link]({
destination: './uploads/', // Save files in "uploads" folder
filename: (req, file, cb) => {
cb(null, [Link] + '-' + [Link]() + [Link]([Link]));
});
// Initialize Multer
const upload = multer({ storage: storage });
// Serve the HTML file
[Link]('/', (req, res) => {
[Link]([Link](__dirname, '[Link]'));
});
// File upload endpoint
[Link]('/upload', [Link]('file'), (req, res) => {
if (![Link]) {
return [Link](400).send('No file uploaded.');
[Link](`File uploaded successfully: ${[Link]}`);
});
// Start the server
[Link](PORT, () => {
[Link](`Server running at [Link]
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<h2>Upload a File</h2>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">Upload</button>
</form>
</body>
</html>
3. Integrate EventEmitter with an Express server. Emit a custom event for each incoming
HTTP request and write a listener that logs the request details.
const express = require('express');
const EventEmitter = require('events');
const app = express();
const PORT = 3000;
// Create an EventEmitter instance
const eventEmitter = new EventEmitter();
// Event listener for logging request details
[Link]('requestReceived', (req) => {
[Link](`Request Received: ${[Link]} ${[Link]} at ${new
Date().toISOString()}`);
});
// Middleware to emit an event on each request
[Link]((req, res, next) => {
[Link]('requestReceived', req);
next();
});
// Sample routes
[Link]('/', (req, res) => {
[Link]('Welcome to EventEmitter in Express!');
});
[Link]('/test', (req, res) => {
[Link]('Test route triggered!');
});
// Start the server
[Link](PORT, () => {
[Link](`Server is running on [Link]
});
Test it
Open a browser / postman and visit:
[Link]
[Link]
In Terminal you will see
Server is running on [Link]
Request Received: GET / at 2025-03-30T12:00:00.000Z
Request Received: GET /test at 2025-03-30T12:00:05.000Z
4. Write a [Link] program that connects to a PostgreSQL database and performs the
following operations:
• Ask the user to choose an operation:
a) Insert data,
b) Update data
c) Delete data
d) View all data
e) Exit
• Perform the corresponding operation based on the user's choice: Repeat the process
until the user chooses to exit.
[Link]
const { insertData, updateData, deleteData, viewData } = require('./crud');
const readline = require('readline-sync');
async function mainMenu() {
while (true) {
[Link]("\nChoose an operation:");
[Link]("1. Insert Data");
[Link]("2. Update Data");
[Link]("3. Delete Data");
[Link]("4. View All Data");
[Link]("5. Exit");
const choice = [Link]("Enter your choice: ");
switch (choice) {
case 1:
await insertData();
break;
case 2:
await updateData();
break;
case 3:
await deleteData();
break;
case 4:
await viewData();
break;
case 5:
[Link]("Exiting program...");
[Link](0);
default:
[Link]("Invalid choice! Please try again.");
// Run the program
mainMenu();
[Link]
const { Client } = require('pg');
const { password } = require('pg/lib/defaults');
require('dotenv').config();
const client = new Client ({
// user: [Link].DB_USER,
// host: [Link].DB_HOST,
// database: [Link].DB_NAME,
// password: [Link].DB_PASSWORD,
// port: [Link].DB_PORT,
host:"localhost",
user:"postgres",
port:5432,
password:"root",
database:"sonu"
})
[Link]()
.then(()=> [Link]("Connection Successfull"))
.catch(err => [Link]("",err));
[Link] = client;
[Link]
const client = require('./dbconfig');
const readline = require('readline-sync');
// Insert Data
const insertData = async () => {
const title = [Link]("Enter article title: ");
const author = [Link]("Enter author name: ");
const content = [Link]("Enter article content: ");
const query = "INSERT INTO articles (title, author, content) VALUES ($1, $2, $3)
RETURNING *";
const values = [title, author, content];
try {
const res = await [Link](query, values);
[Link]("Data inserted successfully:", [Link][0]);
} catch (err) {
[Link]("Error inserting data:", err);
};
// Update Data
const updateData = async () => {
const id = [Link]("Enter article ID to update: ");
const newTitle = [Link]("Enter new title: ");
const newContent = [Link]("Enter new content: ");
const query = "UPDATE articles SET title = $1, content = $2 WHERE id = $3 RETURNING
*";
const values = [newTitle, newContent, id];
try {
const res = await [Link](query, values);
if ([Link] > 0) {
[Link]("Data updated successfully:", [Link][0]);
} else {
[Link]("Article not found.");
} catch (err) {
[Link]("Error updating data:", err);
};
// Delete Data
const deleteData = async () => {
const id = [Link]("Enter article ID to delete: ");
const query = "DELETE FROM articles WHERE id = $1 RETURNING *";
const values = [id];
try {
const res = await [Link](query, values);
if ([Link] > 0) {
[Link]("Article deleted successfully.");
} else {
[Link]("Article not found.");
} catch (err) {
[Link]("Error deleting data:", err);
};
// View All Data
const viewData = async () => {
try {
const res = await [Link]("SELECT * FROM articles ORDER BY id ASC");
[Link]("All Articles:");
[Link]([Link]);
} catch (err) {
[Link]("Error fetching data:", err);
};
[Link] = { insertData, updateData, deleteData, viewData };
npm init -y
npm install pg readline-sync
CREATE TABLE articles (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO articles (title, author, content)
VALUES
('The Future of Artificial Intelligence', 'Elon Musk', 'Artificial Intelligence (AI) is
transforming industries, from healthcare to finance. Experts predict that AI will continue
evolving, improving automation, and enhancing decision-making processes.'),
('Exploring the Depths of the Ocean', 'Sylvia Earle', 'The ocean remains one of the least
explored parts of our planet. Scientists are discovering new species and ecosystems,
highlighting the importance of marine conservation.'),
('The Rise of Electric Vehicles', 'Elon Musk', 'Electric vehicles (EVs) are revolutionizing
transportation. Companies like Tesla are leading the charge, focusing on sustainable
energy and reducing carbon emissions.'),
('The James Webb Space Telescope', 'NASA Scientists', 'NASA’s James Webb Space
Telescope is unlocking new secrets of the universe. Astronomers have already captured
breathtaking images of distant galaxies and star formations.'),
('Climate Change and Its Global Impact', 'Greta Thunberg', 'Climate change is causing
extreme weather events, rising sea levels, and biodiversity loss. Governments and
organizations must take immediate action to mitigate its effects.'),
('The Evolution of Smartphones', 'Steve Jobs', 'From the first iPhone to today’s foldable
devices, smartphones have changed how we communicate, work, and entertain
ourselves. The future holds even more exciting innovations.');
DB_USER=postgres
DB_HOST=localhost
DB_NAME=postgres
DB_PASSWORD=root
DB_PORT=5432
5. Create a [Link] program using Express that allows users to download a file. Your
program should have the following endpoint:
• /download/:filename: Accepts a GET request with a parameter filename.
• The program should read the file with the given filename from the server's file system
and send it as a response.
• If the file does not exist, respond with a 404 status code and a message "File not
found".
const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();
const PORT = 3000;
// Folder where the files are stored
const FILE_DIRECTORY = [Link](__dirname, 'files');
// Endpoint to download a file
[Link]('/download/:filename', (req, res) => {
const filename = [Link];
const filePath = [Link](FILE_DIRECTORY, filename);
// Check if file exists
if ([Link](filePath)) {
[Link](filePath, filename, (err) => {
if (err) {
[Link](500).json({ error: 'Error downloading the file' });
});
} else {
[Link](404).json({ error: 'File not found' });
});
// Start the server
[Link](PORT, () => {
[Link](`Server is running on [Link]
});
//[Link] - run in browser
6. Create an HTTP server that handles JSON data sent in a POST request and serves an
HTML file.
const http = require('http');
const fs = require('fs');
const PORT = 3000;
// Function to serve an HTML file
const serveHTML = (res) => {
[Link]('[Link]', (err, data) => {
if (err) {
[Link](500, { 'Content-Type': 'text/plain' });
[Link]('Internal Server Error');
} else {
[Link](200, { 'Content-Type': 'text/html' });
[Link](data);
});
};
// Create HTTP Server
const server = [Link]((req, res) => {
if ([Link] === 'POST' && [Link] === '/data') {
let body = '';
// Read incoming JSON data
[Link]('data', (chunk) => {
body += [Link]();
});
[Link]('end', () => {
try {
const jsonData = [Link](body);
[Link]('Received JSON:', jsonData);
[Link](200, { 'Content-Type': 'application/json' });
[Link]([Link]({ message: 'Data received successfully', data:
jsonData }));
} catch (error) {
[Link](400, { 'Content-Type': 'application/json' });
[Link]([Link]({ error: 'Invalid JSON format' }));
});
} else if ([Link] === 'GET' && [Link] === '/') {
serveHTML(res);
} else {
[Link](404, { 'Content-Type': 'text/plain' });
[Link]('404 Not Found');
}
});
//Postman
//[Link] - POST
//Body - {"name": "John Doe","age": 30,"city": "New York"}
// Start the Server
[Link](PORT, () => {
[Link](`Server is running at [Link]
});
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple HTTP Server</title>
</head>
<body>
<h1>Welcome to My HTTP Server</h1>
<p>This server can handle JSON data and serve HTML files.</p>
</body>
</html>
7. Build a REST API to Create (POST) and Fetch All Articles (GET) using Express
• Create a POST endpoint/article to insert new article data into PostgreSQL.
• Create a GET endpoint /articles to fetch all articles from PostgreSQL.
• Test both APIs using Postman.
• Output: Successfully inserted article should return a JSON object, and GET should
return all articles.
onst express = require('express');
const { createArticle, getAllArticles } = require('./crud');
const app = express();
[Link]([Link]());
// Create a new article (POST /article)
[Link]('/article', async (req, res) => {
try {
const { title, author, content } = [Link];
if (!title || !author || !content) {
return [Link](400).json({ error: "Title, author, and content are required" });
const newArticle = await createArticle(title, author, content);
[Link](201).json(newArticle);
} catch (err) {
[Link](500).json({ error: "Internal Server Error" });
});
//[Link] - POST
//{"title": "The Rise of Quantum Computing","author": "John Doe","content": "Quantum
computing is set to revolutionize the tech industry with its ability to process complex
computations at unprecedented speeds."}
// Fetch all articles (GET /articles)
[Link]('/articles', async (req, res) => {
try {
const articles = await getAllArticles();
[Link](200).json(articles);
} catch (err) {
[Link](500).json({ error: "Internal Server Error" });
});
//[Link] - GET
// Start the server
const PORT = [Link] || 3000;
[Link](PORT, () => {
[Link](`Server is running on port [Link]
});
[Link]
const pool = require('./dbconfig'); // Ensure [Link] is in the same folder
// Create a new article (POST)
const createArticle = async (title, author, content) => {
const result = await [Link](
'INSERT INTO articles (title, author, content) VALUES ($1, $2, $3) RETURNING *',
[title, author, content]
);
return [Link][0]; // Returns the newly created article
};
// Fetch all articles (GET)
const getAllArticles = async () => {
const result = await [Link]('SELECT * FROM articles');
return [Link]; // Returns all articles as an array
};
[Link] = { createArticle, getAllArticles };
[Link]
const { Client } = require('pg');
require('dotenv').config();
const client = new Client ({
user: [Link].DB_USER,
host: [Link].DB_HOST,
database: [Link].DB_NAME,
password: [Link].DB_PASSWORD,
port: [Link].DB_PORT,
});
[Link]()
.then(()=> [Link]("Connection Successfull"))
.catch(err => [Link]("",err));
[Link] = client;
CREATE TABLE articles (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO articles (title, author, content)
VALUES
('The Future of Artificial Intelligence', 'Elon Musk', 'Artificial Intelligence (AI) is
transforming industries, from healthcare to finance. Experts predict that AI will continue
evolving, improving automation, and enhancing decision-making processes.'),
('Exploring the Depths of the Ocean', 'Sylvia Earle', 'The ocean remains one of the least
explored parts of our planet. Scientists are discovering new species and ecosystems,
highlighting the importance of marine conservation.'),
('The Rise of Electric Vehicles', 'Elon Musk', 'Electric vehicles (EVs) are revolutionizing
transportation. Companies like Tesla are leading the charge, focusing on sustainable
energy and reducing carbon emissions.'),
('The James Webb Space Telescope', 'NASA Scientists', 'NASA’s James Webb Space
Telescope is unlocking new secrets of the universe. Astronomers have already captured
breathtaking images of distant galaxies and star formations.'),
('Climate Change and Its Global Impact', 'Greta Thunberg', 'Climate change is causing
extreme weather events, rising sea levels, and biodiversity loss. Governments and
organizations must take immediate action to mitigate its effects.'),
('The Evolution of Smartphones', 'Steve Jobs', 'From the first iPhone to today’s foldable
devices, smartphones have changed how we communicate, work, and entertain
ourselves. The future holds even more exciting innovations.');
8. Build a REST API to Fetch Specific Article (GET) and updating articles using PUT and
PATCH methods using Express
a. Implement the route /articles/:id to fetch article by ID.
b. Implement a PUT route /article/:id to update the entire article.
c. Implement a PATCH route /article/:id to update partial fields of the article.
d. Test both endpoints via Postman by updating existing articles.
const express = require('express');
const { getArticleById, updateArticle, patchArticle } = require('./crud');
const app = express();
[Link]([Link]());
// Fetch a specific article by ID (GET /articles/:id)
[Link]('/articles/:id', async (req, res) => {
try {
const article = await getArticleById([Link]);
if (!article) {
return [Link](404).json({ error: "Article not found" });
[Link](200).json(article);
} catch (err) {
[Link](500).json({ error: "Internal Server Error" });
});
//[Link] - GET
// Update entire article (PUT /article/:id)
[Link]('/article/:id', async (req, res) => {
try {
const { title, author, content } = [Link];
if (!title || !author || !content) {
return [Link](400).json({ error: "Title, author, and content are required" });
}
const updatedArticle = await updateArticle([Link], title, author, content);
if (!updatedArticle) {
return [Link](404).json({ error: "Article not found" });
[Link](200).json(updatedArticle);
} catch (err) {
[Link](500).json({ error: "Internal Server Error" });
});
//[Link] - PUT
//{"title": "The Future of AI","author": "Elon Musk","content": "Updated content on AI
advancements..."}
// Update partial fields of an article (PATCH /article/:id)
[Link]('/article/:id', async (req, res) => {
try {
const updatedArticle = await patchArticle([Link], [Link]);
if (!updatedArticle) {
return [Link](404).json({ error: "Article not found or no fields updated" });
[Link](200).json(updatedArticle);
} catch (err) {
[Link](500).json({ error: "Internal Server Error" });
}
});
//[Link] - PATCH
//{"content": "AI is changing the world rapidly."}
// Start the server
const PORT = [Link] || 3001;
[Link](PORT, () => {
[Link](`Server is running on port ${PORT}`);
});
[Link]
const pool = require('./dbconfig'); // Make sure [Link] is in the same folder
// Fetch a specific article by ID
const getArticleById = async (id) => {
const result = await [Link](
'SELECT * FROM articles WHERE id = $1',
[id]
);
return [Link][0]; // Returns the article or undefined if not found
};
// Update the entire article (PUT)
const updateArticle = async (id, title, author, content) => {
const result = await [Link](
'UPDATE articles SET title = $1, author = $2, content = $3 WHERE id = $4 RETURNING
*',
[title, author, content, id]
);
return [Link][0]; // Returns the updated article or undefined if not found
};
// Update specific fields of an article (PATCH)
const patchArticle = async (id, fieldsToUpdate) => {
const keys = [Link](fieldsToUpdate);
const values = [Link](fieldsToUpdate);
if ([Link] === 0) return null; // No fields to update
const query = `
UPDATE articles
SET ${[Link]((key, index) => `${key} = $${index + 1}`).join(', ')}
WHERE id = $${[Link] + 1} RETURNING *;
`;
const result = await [Link](query, [...values, id]);
return [Link][0]; // Returns updated article or undefined if not found
};
[Link] = { getArticleById, updateArticle, patchArticle };
[Link]
onst { Client } = require('pg');
require('dotenv').config();
const client = new Client ({
user: 'postgres',
host: 'localhost',
database: 'may',
password: 'root',
port: 5432,
});
[Link]()
.then(()=> [Link]("Connection Successfull"))
.catch(err => [Link]("",err));
[Link] = client;
REATE TABLE articles(
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO articles (title, author, content)
VALUES
('The Future of Artificial Intelligence', 'Elon Musk', 'Artificial Intelligence (AI) is
transforming industries, from healthcare to finance. Experts predict that AI will continue
evolving, improving automation, and enhancing decision-making processes.'),
('Exploring the Depths of the Ocean', 'Sylvia Earle', 'The ocean remains one of the least
explored parts of our planet. Scientists are discovering new species and ecosystems,
highlighting the importance of marine conservation.'),
('The Rise of Electric Vehicles', 'Elon Musk', 'Electric vehicles (EVs) are revolutionizing
transportation. Companies like Tesla are leading the charge, focusing on sustainable
energy and reducing carbon emissions.'),
('The James Webb Space Telescope', 'NASA Scientists', 'NASA’s James Webb Space
Telescope is unlocking new secrets of the universe. Astronomers have already captured
breathtaking images of distant galaxies and star formations.'),
('Climate Change and Its Global Impact', 'Greta Thunberg', 'Climate change is causing
extreme weather events, rising sea levels, and biodiversity loss. Governments and
organizations must take immediate action to mitigate its effects.'),
('The Evolution of Smartphones', 'Steve Jobs', 'From the first iPhone to today’s foldable
devices, smartphones have changed how we communicate, work, and entertain
ourselves. The future holds even more exciting innovations.');
9. Build a REST API to Creating new Article, Delete a Single Article (Row) and all the
Articles (Rows) with POST and DELETE methods using Express
a. Create a DELETE route /article/:id to delete single article by id.
b. Test deletion of an article and handle cases when the article does not exist.
c. Create DELETE route /articles to delete all articles.
d. Test the API via Postman and verify deletion by calling GET /articles (should return
empty array).
const express = require('express');
const { createArticle, deleteArticleById, deleteAllArticles, getAllArticles } =
require('./crud');
const app = express();
[Link]([Link]());
// Route to get all articles (GET /articles) - For Testing
[Link]('/articles', async (req, res) => {
try {
const articles = await getAllArticles();
[Link](200).json(articles);
} catch (err) {
[Link](500).json({ error: "Internal Server Error" });
});
//[Link] - GET
// Route to create a new article (POST /article)
[Link]('/article', async (req, res) => {
try {
const { title,author, content } = [Link];
if (!title || !author || !content) {
return [Link](400).json({ error: "Title and content are required" });
const newArticle = await createArticle(title,author,content);
[Link](201).json(newArticle);
} catch (err) {
[Link](500).json({ error: "Internal Server Error" });
});
//[Link] //
//{"title": "New Article","author": "New Author","content": "This is a new article created
for testing."}
// Route to delete a single article by ID (DELETE /article/:id)
[Link]('/article/:id', async (req, res) => {
try {
const id = [Link];
const deleted = await deleteArticleById(id);
if (deleted) {
[Link](200).json({ message: "Article deleted successfully" });
} else {
[Link](404).json({ error: "Article not found" });
} catch (err) {
[Link](500).json({ error: "Internal Server Error" });
});
//[Link] - DELETE
// Route to delete all articles (DELETE /articles)
[Link]('/articles', async (req, res) => {
try {
const deletedCount = await deleteAllArticles();
[Link](200).json({ message: `Deleted ${deletedCount} articles` });
} catch (err) {
[Link](500).json({ error: "Internal Server Error" });
});
//[Link] - DELETE
// Start the Server
const PORT = [Link] || 3000;
[Link](PORT, () => {
[Link](`Server is running on port [Link]
});
[Link]
const client = require('./dbconfig');
// Create a new article
const createArticle = async (title,author,content) => {
const result = await [Link](
'INSERT INTO articles (title,author,content) VALUES ($1, $2, $3) RETURNING *',
[title,author,content]
);
return [Link][0];
};
// Delete a single article by ID
const deleteArticleById = async (id) => {
const result = await [Link](
'DELETE FROM articles WHERE id = $1 RETURNING *',
[id]
);
return [Link] > 0;
};
// Delete all articles
const deleteAllArticles = async () => {
const result = await [Link]('DELETE FROM articles');
return [Link];
};
// Fetch all articles (for verification)
const getAllArticles = async () => {
const result = await [Link]('SELECT * FROM articles');
return [Link];
};
[Link] = { createArticle, deleteArticleById, deleteAllArticles, getAllArticles };
[Link]
const { Client } = require('pg');
require('dotenv').config();
const client = new Client ({
user: [Link].DB_USER,
host: [Link].DB_HOST,
database: [Link].DB_NAME,
password: [Link].DB_PASSWORD,
port: [Link].DB_PORT,
});
[Link]()
.then(()=> [Link]("Connection Successfull"))
.catch(err => [Link]("",err));
[Link] = client;
CREATE TABLE articles (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO articles (title, author, content)
VALUES
('The Future of Artificial Intelligence', 'Elon Musk', 'Artificial Intelligence (AI) is
transforming industries, from healthcare to finance. Experts predict that AI will continue
evolving, improving automation, and enhancing decision-making processes.'),
('Exploring the Depths of the Ocean', 'Sylvia Earle', 'The ocean remains one of the least
explored parts of our planet. Scientists are discovering new species and ecosystems,
highlighting the importance of marine conservation.'),
('The Rise of Electric Vehicles', 'Elon Musk', 'Electric vehicles (EVs) are revolutionizing
transportation. Companies like Tesla are leading the charge, focusing on sustainable
energy and reducing carbon emissions.'),
('The James Webb Space Telescope', 'NASA Scientists', 'NASA’s James Webb Space
Telescope is unlocking new secrets of the universe. Astronomers have already captured
breathtaking images of distant galaxies and star formations.'),
('Climate Change and Its Global Impact', 'Greta Thunberg', 'Climate change is causing
extreme weather events, rising sea levels, and biodiversity loss. Governments and
organizations must take immediate action to mitigate its effects.'),
('The Evolution of Smartphones', 'Steve Jobs', 'From the first iPhone to today’s foldable
devices, smartphones have changed how we communicate, work, and entertain
ourselves. The future holds even more exciting innovations.');