This commit is contained in:
2024-12-25 03:14:41 +00:00
parent f82ea59048
commit 39574a6599
9 changed files with 389 additions and 274 deletions

View File

@@ -1,62 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tiffy's to-do list website</title>
<meta name="description" content="Tiffy's todo list website" />
<meta name="keywords" content="list, todo" />
<meta name="author" content="Tiffany" />
<link rel="icon" href="images/favicon.ico" />
<link rel="stylesheet" href="css/main.css"/>
</head>
<body>
<section>
<div class="container">
<h1 class="title-text">Tiffy's to-do list website</h1>
<p><i>Add something cute to my to-do list!</i></p>
<img src="images/image.jpg" alt="Image not found">
<form action="/form-action" method="post">
<label for="to-do"></label>
<input name="todo" type="text" placeholder="Enter a to-do" required class="todo-input"/>
<!-- button, if it's a submit button then it will end the form and submit it, other than that the button doesnt do anything -->
<button type="submit" class="form-submit">Add</button>
</form>
<!-- List -->
<!-- ordered list -->
<div class="todo-container">
<div class="inner-todo">
<h1>To do list</h1>
<ol>
<!-- <li>Learn from Ronald</li>
<li>Watch movies</li>
<li>Sleep</li> -->
</ol>
<div class="decor">
<img src="images/cryinggirl.gif"/>
</div>
</div>
</div>
<!-- unordered list -->
<!-- <ul></ul> -->
</div>
</section>
</body>
<script src="js/todo.js"> </script>
</html>

View File

@@ -1,23 +1,24 @@
//importing the dotenv package (secret file), configuring dotenv for our project
//dotenv, secret file, people cant read
import dotenv from 'dotenv';
import dotenv from "dotenv";
dotenv.config({ path: `${__dirname}/../.env` });
//Variable declaration
//we named express as a variable name, usually name same as imported package
//express: designed to easily make a web server
import express, { Request, Response } from 'express';
import express, { Application, Request, Response } from "express";
//bodyParser: sending form action to my server, wrap the user's data in "body" to my server, and my server is unwrapping it
import bodyParser from 'body-parser';
import fs from 'fs';
import bodyParser from "body-parser";
import fs from "fs";
import path from "path";
const filePath = 'todolist.txt';
const filePath: string = "todolist.txt";
//initializing the express web server, everything in express, we want to put in app
const app = express();
const port = process.env.PORT || 3000;
const app: Application = express();
const port: Number = parseInt(process.env.PORT as string) || 3000;
// Middleware
//unwrap the words
@@ -31,45 +32,93 @@ app.use(bodyParser.json());
//to make icon files, because icon files are always downloaded
app.use(express.static(`${__dirname}/../public`));
app.get(`/`, (req, res) => {
res.sendFile(`${__dirname}/index.html`);
app.get(`/`, (_req: Request, res: Response): void => {
res.sendFile(path.join(__dirname, "../public/html/index.html"));
});
app.post('/form-action', (req, res) => {
const todo = req.body.todo;
console.log(todo);
// use fs to add the item to the file
app.post("/form-action", (req: Request, res: Response): void => {
const todo = req.body.todo;
fs.appendFile(filePath, todo + '\n', (err) => {
if (err) {
console.log(err)
res.send("Hey there is an error.")
} else {
res.redirect("/");
}
});
// use fs to add the item to the file
fs.appendFile(filePath, "\n" + todo, (err) => {
if (err) {
console.log(err);
res.send("Hey there is an error.");
} else {
res.redirect("/");
}
});
});
app.get('/get-todos', (req: Request, res: Response): void => {
//Using the fs module to read the file
fs.readFile(filePath, 'utf-8', (err:NodeJS.ErrnoException | null, data: string) => {
if (err) {
console.log(err)
res.send("An error occured.")
} else {
//Return the file contents as a response of each list item data.split
//Send the response back to the client as a json object res.json
res.json(data.split('\n'))
}
})
})
app.get("/get-todos", (_req: Request, res: Response): void => {
//Using the fs module to read the file
fs.readFile(
filePath,
"utf-8",
(err: NodeJS.ErrnoException | null, data: string) => {
if (err) {
console.log(err);
res.send("An error occured.");
} else {
//Return the file contents as a response of each list item data.split
//Send the response back to the client as a json object res.json
res.json(data.split("\n").filter((data) => data.trim() !== ""));
}
}
);
});
app.delete("/delete-todo", (req: Request, res: Response): void => {
const todoToDelete = (req.body.todo || "").trim(); // Ensure input is trimmed
if (!todoToDelete) {
res.status(400).json({ error: "No to-do item provided to delete" });
return;
}
// Read the file to get the current list of todos
fs.readFile(filePath, "utf8", (err, data) => {
if (err) {
console.error("Error reading file:", err);
res.status(500).json({ error: "Internal Server Error" });
return;
}
// Split the content into lines and trim whitespace from each line
const todos = data
.split("\n")
.map((line) => line.trim())
.filter((line) => line !== ""); // Remove empty lines
// Filter out the todo item to delete
const updatedTodos = todos.filter((todo) => todo !== todoToDelete);
if (todos.length === updatedTodos.length) {
res.status(404).json({ error: "Todo not found" });
return;
}
// Join the updated list back into a string
const updatedContent = updatedTodos.join("\n");
// Write the updated content back to the file
fs.writeFile(filePath, updatedContent, "utf8", (writeErr) => {
if (writeErr) {
console.error("Error writing file:", writeErr);
res.status(500).json({ error: "Internal Server Error" });
return;
}
console.log(`Deleted todo: ${todoToDelete}`);
res.status(200).json({ message: "Todo deleted successfully" });
});
});
});
// slash'/' is the home page, /about is the about page
//get, post, put, delete
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
console.log(`Server is running on http://localhost:${port}`);
});

View File

@@ -1,79 +0,0 @@
<!DOCTYPE html>
<!-- document type is html, templating language -->
<html lang="en">
<!-- english -->
<!-- Header section, things that dont show in the webpage, e.g. meta-data: wt language ur website is using, website designed for mobile or actual computers, SEO, title, accessibility issues write it here too-->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Title: the top part of the webpage thingy -->
<title>Document</title>
<!-- Website description -->
<meta name="description" content="Ronald's website" />
<!-- Website keywords -->
<meta name="keywords" content="Ronald, Website:" />
<!-- website author -->
<meta name="author" content="Ronald" />
<!-- Favicon, rel: what type of link, href: where to find the icon -->
<!-- icon: image to icon generator, some pixel restrictions, for the top website icon -->
<link rel="icon" href="images/favicon.ico" />
<!-- CSS styles: called stylesheet, if u type "link: (list of types of link)" then press tab-->
<link rel="stylesheet" href="css/main.css"/>
</head>
<!-- Body: everything in the webpage -->
<body>
<!-- navigation bar -->
<!-- <nav></nav> -->
<!-- sections -->
<section>
<!-- dividers, e.g. left and right side of website -->
<div class="container">
<!-- headers, based on size h1 h2 -->
<h1 class="title-text">Tiffany's to-do list website</h1>
<h2>second header</h2>
<!-- paragraph -->
<p>Welcome to my to-do list</p>
<!-- subtitles -->
<sub></sub>
<!-- bold -->
<b></b>
<!-- italics -->
<i></i>
<!-- underline -->
<u></u>
<!-- image, people usually use avif, webp -->
<!-- alt is alternative -->
<img src="images/image.png" alt="Image not found">
<!-- form, what you want the form to do, usually lead into javascript, login.js -->
<form action="/form-action" method="post">
<label for="to-do">What do you want to do?</label>
<!-- theres different types of input, which is what u fill in for form -->
<!-- type required make it required, placeholders: the invisible list -->
<!-- usually control through javascript -->
<input name="todo" type="text" placeholder="Enter your to-do" required class="todo-input"/>
<!-- button, if it's a submit button then it will end the form and submit it, other than that the button doesnt do anything -->
<button type="submit" class="form-submit">Add to form</button>
</form>
</div>
</section>
</body>
<!-- Footer: the bottom part of the webpage -->
<!-- <footer></footer> -->
<!-- Scripts, where you link javascript files -->
<!-- <scripts src="index.js"> </scripts> -->
</html>