Skip to content

Instantly share code, notes, and snippets.

@yosuke-furukawa
Last active May 11, 2020 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yosuke-furukawa/956a45a2ee85ff4619af27ae97e5c14a to your computer and use it in GitHub Desktop.
Save yosuke-furukawa/956a45a2ee85ff4619af27ae97e5c14a to your computer and use it in GitHub Desktop.
redis protocol implement for server
const net = require('net');
const server = net.createServer();
const CRLF = "\r\n";
const map = new Map();
server.on("connection", (socket) => {
socket.on("data", (command) => {
const c = command.toString();
const cs = c.split(CRLF);
console.log(cs);
const com = cs[2];
const arg1 = cs[4];
const arg2 = cs[6];
if (com === "set") {
set(arg1, arg2);
}
if (com === "get") {
const value = get(arg1);
if (value == null) {
socket.write(`$-1${CRLF}`);
return;
}
socket.write(`+${value}${CRLF}`);
return;
}
if (com === "del") {
del(arg1);
}
if (com === "keys") {
const ks = keys(arg1);
const len = `*${ks.length}`;
const r = [];
ks.forEach((k) => {
r.push(`$${k.length}`);
r.push(k);
});
r.unshift(len);
const result = r.join(CRLF);
console.log(result);
socket.write(`${result}${CRLF}`);
return;
}
if (com === "quit") {
socket.end();
return;
}
socket.write("+OK"+CRLF);
});
});
function set(key, value) {
map.set(key, value);
}
function get(key) {
return map.get(key);
}
function del(key) {
map.delete(key);
}
function keys(pattern) {
const ks = map.keys();
if (pattern === "*") {
return Array.from(ks);
}
}
server.listen(6379);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment