-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07_server.js
77 lines (64 loc) · 1.81 KB
/
07_server.js
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
const fs = require("fs");
const express = require("express");
const exp = require("constants");
const port = process.env.PORT || 1337;
const app = express();
const EventEmitter = require("events");
const chatEmitter = new EventEmitter();
// VERIFY THAT THE CHATEMITTER WORKS
// chatEmitter.on("message", console.log);
// PLAIN-TEXT RESPONSE
function respondText(req, res) {
res.setHeader("Content-Type", "text/plain");
res.end("Hello User");
}
// JSON RESPONSE
function respondJson(req, res) {
res.json({ name: "John Doe" });
}
// DYNAMIC RESPONSE
function respondEcho(req, res) {
const { input = "" } = req.query;
res.json({
normal: input,
shouty: input.toUpperCase(),
characterCount: input.length,
backwards: input.split("").reverse().join(""),
});
}
// 404 RESPONSE
function respondNotFound(req, res) {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
}
// FILE SERVING
function respondStatic(req, res) {
const filename = `${__dirname}/public/${req.params[0]}`;
fs.createReadStream(filename)
.on("error", () => respondNotFound(req, res))
.pipe(res);
}
// CHAT
function respondChat(req, res) {
const { message } = req.query;
chatEmitter.emit("message", message);
}
// SSE - SERVER SENT EVENTS
function respondSSE(req, res) {
res.writeHead(200, {
"Content-Type": "text/event-stream",
Connection: "keep-alive",
});
const onMessage = (msg) => res.write(`data: ${msg}\n\n`);
chatEmitter.on("message", onMessage);
res.on("close", function () {
chatEmitter.off("message", onMessage);
});
}
app.get("/", respondText);
app.get("/json", respondJson);
app.get("/echo", respondEcho);
app.get("/static/*", respondStatic);
app.get("/chat", respondChat);
app.get("/sse", respondSSE);
app.listen(port, () => console.log(`Server listening on port ${port}`));