billywhizz
7/7/2011 - 3:37 PM

line parsing with node.js

line parsing with node.js

var lineParser = function(_command) {
	var _parser = this;
	if(!_command) _command = new Buffer(1024);
	var _loc = 0;
	
	_parser.execute = function(buffer, start, len) {
		var end = start + len;
		if(start > end) {
			if(_parser.onError) _parser.onError(new Error("out of range"));
			return -1;
		}
		var pos = start;
		while (pos < end) {
			switch(String.fromCharCode(buffer[pos])) {
				case "\n":
					if(_parser.onLine) {
						_parser.onLine(_command, 0, _loc);
					}
					_loc = 0;
					break;
				case "\r":
					break;
				default:
					if(_loc >= _command.length) {
						if(_parser.onError) _parser.onError(new Error("command too long"));
						return -1;
					}	
					else {
						_command[_loc++] = buffer[pos];
					}
					break;
			}
			pos++;
		}
		return 0;
	}
	
	_parser.reset = function() {
		_loc = 0;
	}
}

var MAX_LINE = 4096;
var p = new lineParser(new Buffer(MAX_LINE));
var b = new Buffer("line one\r\nline two\r\nline three\r\n");

p.onError = function(err) {
	console.log(JSON.stringify(err));
};

p.onLine = function(buffer, start, end) {
	console.log(buffer.toString("utf8", start, end));
};

if(p.execute(b, 0, b.length) != 0) {
	console.log("parse failed");
}