-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
61 lines (57 loc) · 1.57 KB
/
index.js
File metadata and controls
61 lines (57 loc) · 1.57 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
61
import http from "node:http";
import { readFile } from "node:fs/promises";
import { Buffer } from "node:buffer";
const todos = [
{
id: 1,
title: "Check Emails",
},
{
id: 2,
title: "Buy Rice",
},
];
const sendTodosReposne = (res) => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(todos));
};
const server = http.createServer((req, res) => {
switch (req.url) {
case "/todos":
if (req.method === "GET") {
sendTodosReposne(res);
} else {
let reqBody = [];
req
.on("data", (chunk) => {
reqBody.push(chunk);
})
.on("end", () => {
reqBody = JSON.parse(Buffer.concat(reqBody).toString());
if (req.method === "POST") {
todos.push({
id: todos[todos.length - 1].id + 1,
title: reqBody.title,
});
sendTodosReposne(res);
} else if (req.method === "DELETE") {
const indexOfTodo = todos.findIndex(
(todo) => todo.id === reqBody.id
);
todos.splice(indexOfTodo, 1);
sendTodosReposne(res);
}
});
}
break;
case "/":
const filePath = new URL("./index.html", import.meta.url);
readFile(filePath, { encoding: "utf8" }).then((htmlContent) => {
res.writeHead(200, { "Content-Type": "text/html" });
res.end(htmlContent);
});
}
});
server.listen(8000, () => {
console.log("Server is running on http://localhost:8000");
});