KEMBAR78
Allnode | PDF | Climate Change | Electric Vehicle
0% found this document useful (0 votes)
6 views30 pages

Allnode

The document outlines multiple Node.js applications using Express and other libraries. It includes creating a simple HTTP server, handling file uploads, integrating EventEmitter, connecting to a PostgreSQL database for CRUD operations, serving downloadable files, handling JSON data, and building a REST API for articles. Each section provides code snippets and explanations for the functionalities implemented.

Uploaded by

shettyyashwin569
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views30 pages

Allnode

The document outlines multiple Node.js applications using Express and other libraries. It includes creating a simple HTTP server, handling file uploads, integrating EventEmitter, connecting to a PostgreSQL database for CRUD operations, serving downloadable files, handling JSON data, and building a REST API for articles. Each section provides code snippets and explanations for the functionalities implemented.

Uploaded by

shettyyashwin569
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

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 = http.createServer((req, res) => {
8. res.writeHead(200, { 'Content-Type': 'text/plain' });
9. res.end('Hello, World!\n');
10. });
11.
12. // Start the server
13. server.listen(PORT, () => {
14. console.log(`Server running at http://localhost:$
{PORT}/`);
15. });
16.

2.Create 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 = multer.diskStorage({

destination: './uploads/', // Save files in "uploads" folder

filename: (req, file, cb) => {

cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));

});
// Initialize Multer

const upload = multer({ storage: storage });

// Serve the HTML file

app.get('/', (req, res) => {

res.sendFile(path.join(__dirname, 'index.html'));

});

// File upload endpoint

app.post('/upload', upload.single('file'), (req, res) => {

if (!req.file) {

return res.status(400).send('No file uploaded.');

res.send(`File uploaded successfully: ${req.file.filename}`);

});

// Start the server

app.listen(PORT, () => {

console.log(`Server running at http://localhost:${PORT}`);

});

<!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

eventEmitter.on('requestReceived', (req) => {

console.log(`Request Received: ${req.method} ${req.url} at ${new


Date().toISOString()}`);

});

// Middleware to emit an event on each request

app.use((req, res, next) => {


eventEmitter.emit('requestReceived', req);

next();

});

// Sample routes

app.get('/', (req, res) => {

res.send('Welcome to EventEmitter in Express!');

});

app.get('/test', (req, res) => {

res.send('Test route triggered!');

});

// Start the server

app.listen(PORT, () => {

console.log(`Server is running on http://localhost:${PORT}`);

});

Test it

Open a browser / postman and visit:

http://localhost:3000/

http://localhost:3000/test

In Terminal you will see

Server is running on http://localhost:3000

Request Received: GET / at 2025-03-30T12:00:00.000Z

Request Received: GET /test at 2025-03-30T12:00:05.000Z


4. Write a Node.js 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.

App.js

const { insertData, updateData, deleteData, viewData } = require('./crud');

const readline = require('readline-sync');

async function mainMenu() {

while (true) {

console.log("\nChoose an operation:");

console.log("1. Insert Data");

console.log("2. Update Data");

console.log("3. Delete Data");

console.log("4. View All Data");

console.log("5. Exit");

const choice = readline.questionInt("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:

console.log("Exiting program...");

process.exit(0);

default:

console.log("Invalid choice! Please try again.");

// Run the program

mainMenu();

dbconfig.js

const { Client } = require('pg');

const { password } = require('pg/lib/defaults');

require('dotenv').config();
const client = new Client ({

// user: process.env.DB_USER,

// host: process.env.DB_HOST,

// database: process.env.DB_NAME,

// password: process.env.DB_PASSWORD,

// port: process.env.DB_PORT,

host:"localhost",

user:"postgres",

port:5432,

password:"root",

database:"sonu"

})

client.connect()

.then(()=> console.log("Connection Successfull"))

.catch(err => console.log("",err));

module.exports = client;

crud.js

const client = require('./dbconfig');

const readline = require('readline-sync');

// Insert Data

const insertData = async () => {


const title = readline.question("Enter article title: ");

const author = readline.question("Enter author name: ");

const content = readline.question("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 client.query(query, values);

console.log("Data inserted successfully:", res.rows[0]);

} catch (err) {

console.error("Error inserting data:", err);

};

// Update Data

const updateData = async () => {

const id = readline.questionInt("Enter article ID to update: ");

const newTitle = readline.question("Enter new title: ");

const newContent = readline.question("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 client.query(query, values);

if (res.rowCount > 0) {
console.log("Data updated successfully:", res.rows[0]);

} else {

console.log("Article not found.");

} catch (err) {

console.error("Error updating data:", err);

};

// Delete Data

const deleteData = async () => {

const id = readline.questionInt("Enter article ID to delete: ");

const query = "DELETE FROM articles WHERE id = $1 RETURNING *";

const values = [id];

try {

const res = await client.query(query, values);

if (res.rowCount > 0) {

console.log("Article deleted successfully.");

} else {

console.log("Article not found.");

} catch (err) {

console.error("Error deleting data:", err);

};
// View All Data

const viewData = async () => {

try {

const res = await client.query("SELECT * FROM articles ORDER BY id ASC");

console.log("All Articles:");

console.table(res.rows);

} catch (err) {

console.error("Error fetching data:", err);

};

module.exports = { 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 Node.js 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 = path.join(__dirname, 'files');

// Endpoint to download a file

app.get('/download/:filename', (req, res) => {

const filename = req.params.filename;

const filePath = path.join(FILE_DIRECTORY, filename);

// Check if file exists

if (fs.existsSync(filePath)) {

res.download(filePath, filename, (err) => {

if (err) {

res.status(500).json({ error: 'Error downloading the file' });

});

} else {

res.status(404).json({ error: 'File not found' });

});
// Start the server

app.listen(PORT, () => {

console.log(`Server is running on http://localhost:${PORT}`);

});

//http://localhost:3000/download/filename.extension - 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) => {

fs.readFile('index.html', (err, data) => {

if (err) {

res.writeHead(500, { 'Content-Type': 'text/plain' });

res.end('Internal Server Error');

} else {

res.writeHead(200, { 'Content-Type': 'text/html' });

res.end(data);

});

};

// Create HTTP Server


const server = http.createServer((req, res) => {

if (req.method === 'POST' && req.url === '/data') {

let body = '';

// Read incoming JSON data

req.on('data', (chunk) => {

body += chunk.toString();

});

req.on('end', () => {

try {

const jsonData = JSON.parse(body);

console.log('Received JSON:', jsonData);

res.writeHead(200, { 'Content-Type': 'application/json' });

res.end(JSON.stringify({ message: 'Data received successfully', data:


jsonData }));

} catch (error) {

res.writeHead(400, { 'Content-Type': 'application/json' });

res.end(JSON.stringify({ error: 'Invalid JSON format' }));

});

} else if (req.method === 'GET' && req.url === '/') {

serveHTML(res);

} else {

res.writeHead(404, { 'Content-Type': 'text/plain' });

res.end('404 Not Found');

}
});

//Postman

//http://localhost:3000/data - POST

//Body - {"name": "John Doe","age": 30,"city": "New York"}

// Start the Server

server.listen(PORT, () => {

console.log(`Server is running at http://localhost:${PORT}`);

});

Index.html

<!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();

app.use(express.json());

// Create a new article (POST /article)

app.post('/article', async (req, res) => {

try {

const { title, author, content } = req.body;

if (!title || !author || !content) {

return res.status(400).json({ error: "Title, author, and content are required" });

const newArticle = await createArticle(title, author, content);

res.status(201).json(newArticle);

} catch (err) {

res.status(500).json({ error: "Internal Server Error" });

});

//http://localhost:3000/article - 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)


app.get('/articles', async (req, res) => {

try {

const articles = await getAllArticles();

res.status(200).json(articles);

} catch (err) {

res.status(500).json({ error: "Internal Server Error" });

});

//http://localhost:3000/articles - GET

// Start the server

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {

console.log(`Server is running on port http://localhost:${PORT}`);

});

Crud.js

const pool = require('./dbconfig'); // Ensure dbconfig.js is in the same folder

// Create a new article (POST)

const createArticle = async (title, author, content) => {

const result = await pool.query(

'INSERT INTO articles (title, author, content) VALUES ($1, $2, $3) RETURNING *',

[title, author, content]

);

return result.rows[0]; // Returns the newly created article

};
// Fetch all articles (GET)

const getAllArticles = async () => {

const result = await pool.query('SELECT * FROM articles');

return result.rows; // Returns all articles as an array

};

module.exports = { createArticle, getAllArticles };

dbconfig.js

const { Client } = require('pg');

require('dotenv').config();

const client = new Client ({

user: process.env.DB_USER,

host: process.env.DB_HOST,

database: process.env.DB_NAME,

password: process.env.DB_PASSWORD,

port: process.env.DB_PORT,

});

client.connect()

.then(()=> console.log("Connection Successfull"))

.catch(err => console.log("",err));

module.exports = 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();

app.use(express.json());

// Fetch a specific article by ID (GET /articles/:id)

app.get('/articles/:id', async (req, res) => {

try {

const article = await getArticleById(req.params.id);

if (!article) {

return res.status(404).json({ error: "Article not found" });

res.status(200).json(article);

} catch (err) {

res.status(500).json({ error: "Internal Server Error" });

});

//http://localhost:3000/articles/1 - GET

// Update entire article (PUT /article/:id)

app.put('/article/:id', async (req, res) => {

try {

const { title, author, content } = req.body;

if (!title || !author || !content) {

return res.status(400).json({ error: "Title, author, and content are required" });
}

const updatedArticle = await updateArticle(req.params.id, title, author, content);

if (!updatedArticle) {

return res.status(404).json({ error: "Article not found" });

res.status(200).json(updatedArticle);

} catch (err) {

res.status(500).json({ error: "Internal Server Error" });

});

//http://localhost:3000/article/1 - PUT

//{"title": "The Future of AI","author": "Elon Musk","content": "Updated content on AI


advancements..."}

// Update partial fields of an article (PATCH /article/:id)

app.patch('/article/:id', async (req, res) => {

try {

const updatedArticle = await patchArticle(req.params.id, req.body);

if (!updatedArticle) {

return res.status(404).json({ error: "Article not found or no fields updated" });

res.status(200).json(updatedArticle);

} catch (err) {

res.status(500).json({ error: "Internal Server Error" });

}
});

//http://localhost:3000/article/1 - PATCH

//{"content": "AI is changing the world rapidly."}

// Start the server

const PORT = process.env.PORT || 3001;

app.listen(PORT, () => {

console.log(`Server is running on port ${PORT}`);

});

Crud.js

const pool = require('./dbconfig'); // Make sure dbconfig.js is in the same folder

// Fetch a specific article by ID

const getArticleById = async (id) => {

const result = await pool.query(

'SELECT * FROM articles WHERE id = $1',

[id]

);

return result.rows[0]; // Returns the article or undefined if not found

};

// Update the entire article (PUT)

const updateArticle = async (id, title, author, content) => {

const result = await pool.query(

'UPDATE articles SET title = $1, author = $2, content = $3 WHERE id = $4 RETURNING
*',
[title, author, content, id]

);

return result.rows[0]; // Returns the updated article or undefined if not found

};

// Update specific fields of an article (PATCH)

const patchArticle = async (id, fieldsToUpdate) => {

const keys = Object.keys(fieldsToUpdate);

const values = Object.values(fieldsToUpdate);

if (keys.length === 0) return null; // No fields to update

const query = `

UPDATE articles

SET ${keys.map((key, index) => `${key} = $${index + 1}`).join(', ')}

WHERE id = $${keys.length + 1} RETURNING *;

`;

const result = await pool.query(query, [...values, id]);

return result.rows[0]; // Returns updated article or undefined if not found

};

module.exports = { getArticleById, updateArticle, patchArticle };

dbconfig.js

onst { Client } = require('pg');

require('dotenv').config();
const client = new Client ({

user: 'postgres',

host: 'localhost',

database: 'may',

password: 'root',

port: 5432,

});

client.connect()

.then(()=> console.log("Connection Successfull"))

.catch(err => console.log("",err));

module.exports = 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();

app.use(express.json());

// Route to get all articles (GET /articles) - For Testing

app.get('/articles', async (req, res) => {


try {

const articles = await getAllArticles();

res.status(200).json(articles);

} catch (err) {

res.status(500).json({ error: "Internal Server Error" });

});

//http://localhost:3000/articles - GET

// Route to create a new article (POST /article)

app.post('/article', async (req, res) => {

try {

const { title,author, content } = req.body;

if (!title || !author || !content) {

return res.status(400).json({ error: "Title and content are required" });

const newArticle = await createArticle(title,author,content);

res.status(201).json(newArticle);

} catch (err) {

res.status(500).json({ error: "Internal Server Error" });

});

//http://localhost:3000/article-POST //

//{"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)

app.delete('/article/:id', async (req, res) => {


try {

const id = req.params.id;

const deleted = await deleteArticleById(id);

if (deleted) {

res.status(200).json({ message: "Article deleted successfully" });

} else {

res.status(404).json({ error: "Article not found" });

} catch (err) {

res.status(500).json({ error: "Internal Server Error" });

});

//http://localhost:3000/article/8 - DELETE

// Route to delete all articles (DELETE /articles)

app.delete('/articles', async (req, res) => {

try {

const deletedCount = await deleteAllArticles();

res.status(200).json({ message: `Deleted ${deletedCount} articles` });

} catch (err) {

res.status(500).json({ error: "Internal Server Error" });

});

//http://localhost:3000/articles - DELETE

// Start the Server

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
console.log(`Server is running on port http://localhost:${PORT}`);

});

Crud.js

const client = require('./dbconfig');

// Create a new article

const createArticle = async (title,author,content) => {

const result = await client.query(

'INSERT INTO articles (title,author,content) VALUES ($1, $2, $3) RETURNING *',

[title,author,content]

);

return result.rows[0];

};

// Delete a single article by ID

const deleteArticleById = async (id) => {

const result = await client.query(

'DELETE FROM articles WHERE id = $1 RETURNING *',

[id]

);

return result.rowCount > 0;

};

// Delete all articles

const deleteAllArticles = async () => {

const result = await client.query('DELETE FROM articles');

return result.rowCount;
};

// Fetch all articles (for verification)

const getAllArticles = async () => {

const result = await client.query('SELECT * FROM articles');

return result.rows;

};

module.exports = { createArticle, deleteArticleById, deleteAllArticles, getAllArticles };

dbconfig.js

const { Client } = require('pg');

require('dotenv').config();

const client = new Client ({

user: process.env.DB_USER,

host: process.env.DB_HOST,

database: process.env.DB_NAME,

password: process.env.DB_PASSWORD,

port: process.env.DB_PORT,

});

client.connect()

.then(()=> console.log("Connection Successfull"))

.catch(err => console.log("",err));

module.exports = 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.');

You might also like