-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
51 lines (43 loc) · 1.34 KB
/
server.js
File metadata and controls
51 lines (43 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const express = require("express");
const fs = require("fs");
const path = require("path");
const app = express();
const PORT = process.env.PORT || 3000;
const FILE_PATH = path.join(__dirname, "tasks.json");
app.use(express.json());
app.use(express.static(__dirname)); // Serves index.html
const readTasks = () => JSON.parse(fs.readFileSync(FILE_PATH));
const writeTasks = (tasks) =>
fs.writeFileSync(FILE_PATH, JSON.stringify(tasks, null, 2));
// Routes
app.get("/api/tasks", (req, res) => {
res.json(readTasks());
});
app.post("/api/tasks", (req, res) => {
const tasks = readTasks();
const newTask = {
id: Date.now(),
title: req.body.title || "Untitled Task",
completed: false,
};
tasks.push(newTask);
writeTasks(tasks);
res.status(201).json(newTask);
});
app.put("/api/tasks/:id", (req, res) => {
const tasks = readTasks();
const task = tasks.find((t) => t.id === parseInt(req.params.id));
if (!task) return res.status(404).json({ error: "Task not found" });
task.completed = true;
writeTasks(tasks);
res.json(task);
});
app.delete("/api/tasks/:id", (req, res) => {
const tasks = readTasks();
const updated = tasks.filter((t) => t.id !== parseInt(req.params.id));
writeTasks(updated);
res.json({ message: "Task deleted" });
});
app.listen(PORT, () =>
console.log(`Server running at http://localhost:${PORT}`)
);