Skip to content

Instantly share code, notes, and snippets.

@bmeck
Created August 22, 2011 19:58
Show Gist options
  • Save bmeck/1163360 to your computer and use it in GitHub Desktop.
Save bmeck/1163360 to your computer and use it in GitHub Desktop.
// A subclass of Socket which reads data by line
var net = require('net');
var util = require('util');
function Socket(options) {
if (!(this instanceof Socket)) return new Socket(options);
net.Socket.call(this, options);
this.current_data = [];
this.on('data', this.process_data);
this.on('end', this.process_end);
}
util.inherits(Socket, net.Socket);
exports.Socket = Socket;
var separator = '\n'.charCodeAt(0);
Socket.prototype.process_data = function process_data(data) {
if(typeof data === 'string') {
return process_data(new Buffer(data));
}
var current_data = this.current_data;
var results;
var l = data.length;
var start = 0;
for(var i = 0; i < l;) {
if(data[i++] === separator) {
if(current_data.length) {
var this_line = current_data.join('') + data.slice(start, i);
current_data = this.current_data = [];
}
else {
var this_line = data.slice(start, i).toString();
}
start = i;
this.emit('line', this_line);
}
}
if(start != l) {
current_data[current_data.length] = data;
}
};
Socket.prototype.process_end = function () {
if (this.current_data.length)
this.emit('line', this.current_data.join(''))
this.current_data = [];
};
@baudehlo
Copy link

baudehlo commented Sep 1, 2011

I benchmarked this (using smtp-source from postfix) and it doesn't seem to be any faster. To be honest the bottleneck in Haraka is probably elsewhere.

@bmeck
Copy link
Author

bmeck commented Sep 1, 2011 via email

@baudehlo
Copy link

baudehlo commented Sep 1, 2011

Do you use anything for profiling in node?

@bmeck
Copy link
Author

bmeck commented Sep 1, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment