-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·58 lines (50 loc) · 1.43 KB
/
server.js
File metadata and controls
executable file
·58 lines (50 loc) · 1.43 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
#! /usr/bin/env node
const { createServer } = require("node:net");
const Deserializer = require("./deserialize");
const Serializer = require("./serialize");
const handleCommand = require("./commands");
const { loadOnStartup } = require("./commands/save");
class RedisServer {
constructor(port) {
this.port = port;
this.server = this.createTCPServer();
this.serverListen();
}
createTCPServer() {
loadOnStartup();
return createServer((socket) => {
socket.on("data", (chunk) => {
try {
// data is in RESP
const data = chunk.toString("utf-8");
this.analyseData(data, socket);
} catch (e) {
this.handleError(e, socket);
}
});
socket.on("end", () => {
console.log(
`Connection to socket ${socket.remoteAddress} on port ${socket.remotePort} has been terminated`
);
});
socket.on("error", (err) => {
console.error(err.message);
socket.end();
});
});
}
serverListen() {
this.server.listen(this.port, () => {
console.log(`TCP server listening on ${this.port}`);
});
}
analyseData(request, socket) {
const data = new Deserializer(request).deserialize();
socket.write(handleCommand(data, socket));
}
handleError(error, socket) {
console.error(error.message);
socket.write(new Serializer(new Error(error.message)).serialize());
}
}
new RedisServer(6379);