Created
July 7, 2011 15:37
-
-
Save billywhizz/1069779 to your computer and use it in GitHub Desktop.
line parsing with node.js
This file contains hidden or 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
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"); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment