-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
60 lines (49 loc) · 1.25 KB
/
Copy pathserver.js
File metadata and controls
60 lines (49 loc) · 1.25 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
52
53
54
55
56
57
58
59
60
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import fs from 'fs';
const app = express();
const port = 5000;
app.use(cors());
app.use(bodyParser.json());
const tasksFilePath = 'tasks.json';
const loadTasksFromFile = () => {
if (fs.existsSync(tasksFilePath)) {
const rawData = fs.readFileSync(tasksFilePath);
return JSON.parse(rawData);
}
return [];
};
const saveTasksToFile = () => {
fs.writeFileSync(tasksFilePath, JSON.stringify(tasks, null, 2));
};
let tasks = loadTasksFromFile();
app.get('/tasks', (req, res) => {
res.json({ tasks });
});
app.put('/tasks', (req, res) => {
const { tasks: updatedTasks } = req.body;
tasks = updatedTasks;
saveTasksToFile();
res.status(200).json({ message: 'Tasks updated' });
});
app.post('/tasks', (req, res) => {
const { title } = req.body;
const newTask = {
id: Date.now(),
title,
completed: false
};
tasks.push(newTask);
saveTasksToFile();
res.status(201).json(newTask);
});
app.delete('/tasks/:id', (req, res) => {
const { id } = req.params;
tasks = tasks.filter((task) => task.id != id);
saveTasksToFile();
res.status(200).json({ message: 'Task deleted' });
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});