Gagle/Node-BufferedReader — pull request #1 by moos (2012-05-12 21:39:56+00:00)
Title: Adding byteoffset and line no. to callbacks.

Hi Gabriel,

Thanks for this nice package. I needed a way to get the byte offset of the line I was reading, so I wend ahead and added the byte offset to the callback for the 'byte', 'character', 'buffer', and 'line' events. 'line' event also gets the line no.

Sorry for the white-space mix up, I have it set to no-tabs. If you do a 'git diff --ignore-all-space' you'll see just the changes.

Also I did a bit of optimization on the event callbacks. Don't know if it makes much difference, but better to be on the safe side. (I'm reading multi MB files).

Should probably add test cases if you decide to incorporate these.

Best,
moos

Here's the diff less white-space clutter:
```
diff --git a/src/buffered-reader.js b/src/buffered-reader.js
index c7352bb..42c86c8 100644
--- a/src/buffered-reader.js
+++ b/src/buffered-reader.js
@@ -70,9 +70,14 @@ BufferedReader.prototype.read = function (){
var lastChunk;
var buffer;
var me = this;
+ var lineOffset = 0,
+ lineCount = 0,
+ byteOffset = 0;

-	var loop = this.listeners ("character").length !== 0 || this.listeners ("line").length !== 0 ||
-	this.listeners ("byte").length !== 0;
+ var onChar = this.listeners ("character").length !== 0,
+ onLine = this.listeners ("line").length !== 0,
+ onByte = this.listeners ("byte").length !== 0,
+ loop = onChar || onLine || onByte;

stream.on ("data", function (data){
buffer = data;
@@ -87,26 +92,30 @@ BufferedReader.prototype.read = function (){

character = data[i];
if (stream.encoding){
-	me.emit ("character", character === "\r" ? "\n" : character);
+ onChar && me.emit ("character", character === "\r" ? "\n" : character, byteOffset + i);
}else{
-	me.emit ("byte", character);
+ onByte && me.emit ("byte", character, byteOffset + i);
continue;
}

+ if (!onLine) continue;
if (character === "\n" || character === "\r"){
chunk = data.slice (offset, i);
-	offset = i + 1;

if (lastChunk){
chunk = lastChunk.concat (chunk);
-	lastChunk = null;
}

if (i + 1 !== len && character === "\r" && data[i + 1] === "\n"){
i++;
}

-	me.emit ("line", chunk);
+ me.emit ("line", chunk, lineOffset + offset, ++lineCount);
+ offset = i + 1;
+ if (lastChunk){
+ lineOffset += lastChunk.length;
+ lastChunk = null;
+ }
}
}

@@ -114,14 +123,17 @@ BufferedReader.prototype.read = function (){
var s = offset === 0 ? data : data.slice (offset);
lastChunk = lastChunk ? lastChunk.concat (s) : s;
}
+ lineOffset += offset;
}

-	me.emit ("buffer", data);
+ me.emit ("buffer", data, byteOffset);
if (me._interrupted){
me._interrupted = false;
stream.destroy ();
me.emit ("end");
}
+ byteOffset += len;
+
});

stream.on ("end", function (){
```