Skip to content

Instantly share code, notes, and snippets.

@vstarck
Created November 25, 2012 03:22
Show Gist options
  • Save vstarck/4142279 to your computer and use it in GitHub Desktop.
Save vstarck/4142279 to your computer and use it in GitHub Desktop.
nodecache.js
var net = require('net');
var OPTS = {
port: 5544
};
process.argv.forEach(function (val, index, array) {
var key, value;
key = val.split('=')[0];
value = val.split('=')[1];
if (OPTS[key]) {
OPTS[key] = value;
}
});
var cache = {
};
var methods = {
size: function (socket) {
socket.write(Object.keys(cache).length.toString());
},
list: function (socket) {
Object.keys(cache).forEach(function (key) {
socket.write(key + ' => ' + cache[key] + "\r\n");
});
},
set: function (socket, key, value) {
cache[key] = value;
socket.write('STORED');
},
get: function (socket, key) {
socket.write('VALUE ' + (cache[key] || 'null') + "\r\n");
}
};
function digester(data, socket) {
var parts = /(size|set|get|list)\s?([^\s]+)?\s?(.+)?(\r\n)?/.exec(data);
if (!parts) {
return;
}
// discard the original string
parts.shift();
var method = parts.shift();
if (methods[method]) {
parts.unshift(socket);
methods[method].apply(methods, parts);
}
}
var server = net.createServer(function (socket) {
socket.setEncoding('utf8');
socket.on('data', function (chunk) {
digester(chunk, socket);
});
});
server.listen(OPTS.port, '127.0.0.1');
console.log('Nodecache running at http://127.0.0.1:' + OPTS.port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment