-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
87 lines (80 loc) · 2.1 KB
/
index.js
File metadata and controls
87 lines (80 loc) · 2.1 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const http = require("http");
const url = require("url");
const fs = require("fs");
const events = require("events");
const eventEmitter = new events.EventEmitter();
eventEmitter.on("exampleEvent", ({ res, name, roll }) => {
res.write(`the roll of ${name} is ${roll}`);
res.end();
});
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
if (req.url === "/" && req.method === "GET") {
fs.readFile("./welcome.html", (err, data) => {
if (data) {
res.write(data);
res.end();
} else {
res.write(err);
res.end();
}
});
} else if ((req.url === "/get-body", req.method === "POST")) {
const data = [];
req.on("data", (chunk) => {
data.push(chunk);
});
req.on("end", () => {
const parsedData = Buffer.concat(data).toString();
const name = JSON.parse(parsedData).name;
res.write(name);
res.end();
});
} else if (parsedUrl.query.checkUrl) {
res.write("url module is working");
res.end();
} else if (req.url === "/readme") {
fs.readFile("./myself.json", (err, data) => {
if (data) {
res.write(data);
res.end();
} else {
res.write(err);
res.end();
}
});
} else if (req.url === "/create-junk") {
fs.writeFile("./junk.txt", "siam", (err) => {
if (err) {
res.write(err);
res.end();
}
});
res.end();
} else if (req.url === "/delete-junk") {
fs.unlink("./junk.txt", (err) => {
if (err) {
res.write(err);
res.end();
}
});
} else if (req.url === "/event") {
eventEmitter.emit("exampleEvent", { res, name: "siam", roll: 559718 });
} else {
res.write("unknown route");
res.end();
}
});
server.listen(5000);
// stream throw fs
// const readme = fs.createReadStream("./myself.json");
// const data = [];
// readme.on("data", (chunk) => {
// data.push(chunk);
// });
// readme.on("end", () => {
// const parsedData = Buffer.concat(data).toString();
// const name = JSON.parse(parsedData).name;
// res.write(name);
// res.end();
// });