Created
July 25, 2013 14:18
-
-
Save sergi/6080125 to your computer and use it in GitHub Desktop.
Naive redis GET/SET server for Node.js. Version 2, no dependencies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var net = require('net'); | |
var db = Object.create(null); | |
net.createServer(function(socket) { | |
function sendError(err) { | |
console.error(err); | |
socket.write("-ERR " + err + "\r\n") | |
} | |
function execute(cmdArgs) { | |
var name = cmdArgs[0]; | |
var first = cmdArgs[1]; | |
if (name === 'GET') { | |
if (cmdArgs.length < 1) { | |
sendError("GET expects 1 argument"); | |
return; | |
} | |
socket.write('$' + db[first].length + '\r\n' + first + '\r\n'); | |
} | |
else if (name === 'SET') { | |
if (cmdArgs.length < 2) { | |
sendError("SET expects 2 arguments"); | |
return; | |
} | |
db[first] = cmdArgs[1]; | |
socket.write('+OK\r\n'); | |
} | |
else { | |
sendError("Unknown command: #" + name + "#"); | |
} | |
} | |
var waitForCmd = false; | |
var argc = 0; | |
var args = []; | |
var offset = 0; | |
function processLine(line) { | |
if (waitForCmd) { | |
waitForCmd = false; | |
args.push(line); | |
argc -= 1; | |
if (argc === 0) { | |
execute(args); | |
args = []; | |
} | |
return; | |
} | |
if (!line) return; | |
if (line.charAt(0) === '*') { | |
argc = parseInt(line.substr(1)); | |
return; | |
} | |
else if (argc > 0 && line.charAt(0) === '$') { | |
waitForCmd = true; | |
} | |
else { | |
sendError('Unexpected operation "' + line + '"') | |
} | |
} | |
socket.on('readable', function() { | |
var buf = socket.read(); | |
if (!buf) return; | |
for (; offset < buf.length; offset++) { | |
if (buf[offset] === 0x0d) { | |
processLine(buf.slice(0, offset).toString()); | |
buf = buf.slice(offset + 2); // account for \r\n | |
offset = 0; | |
socket.unshift(buf); | |
return; | |
} | |
} | |
socket.unshift(buf); | |
}); | |
socket.on('error', function(e) { console.log(e) }); | |
}).listen(6379); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment