Skip to content
This repository was archived by the owner on Feb 13, 2022. It is now read-only.
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions lib/memcache.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@
*/

var tcp = require('net'),
util = require('util');
util = require('util'),
EventEmitter = require('events');

var crlf = "\r\n";
var crlf_len = crlf.length;
var self;

var error_replies = ['ERROR', 'NOT_FOUND', 'CLIENT_ERROR', 'SERVER_ERROR'];

Expand All @@ -42,12 +44,12 @@ var Client = exports.Client = function(port, host) {
this.handles = [];
};

util.inherits(Client, process.EventEmitter);
util.inherits(Client, EventEmitter);

Client.prototype.connect = function () {
if (!this.conn) {
this.conn = new tcp.createConnection(this.port, this.host);
var self = this;
self = this;
this.conn.addListener("connect", function () {
this.setTimeout(0); // try to stay connected.
this.setNoDelay();
Expand Down Expand Up @@ -107,7 +109,12 @@ Client.prototype.dispatchHandles = function() {
Client.prototype.query = function(query, type, callback) {
this.callbacks.push({ type: type, fun: callback });
this.sends++;
this.conn.write(query + crlf);
if (this.conn !== null) {
this.conn.write(query + crlf);
} else {
// Server has crashed or in another way become unavailable, connection closed.
self.emit("close");
}
};

Client.prototype.close = function() {
Expand Down Expand Up @@ -271,11 +278,11 @@ Client.prototype.handle_get = function(buffer) {
var end_indicator_len = 3;
var result_len = 0;

if (buffer.indexOf('END') == 0) {
if (buffer.lastIndexOf('END') == 0) {
return [result_value, end_indicator_len + crlf_len];
} else if (buffer.indexOf('VALUE') == 0 && buffer.indexOf('END') != -1) {
} else if (buffer.indexOf('VALUE') == 0 && buffer.lastIndexOf('END') != -1) {
first_line_len = buffer.indexOf(crlf) + crlf_len;
var end_indicator_start = buffer.indexOf('END');
var end_indicator_start = buffer.lastIndexOf('END');
result_len = end_indicator_start - first_line_len - crlf_len;
result_value = buffer.substr(first_line_len, result_len);
return [result_value, first_line_len + parseInt(result_len, 10) + crlf_len + end_indicator_len + crlf_len]
Expand Down