Created
August 8, 2012 07:13
-
-
Save fxsjy/3293029 to your computer and use it in GitHub Desktop.
QBuffer: A little buffer tool for Node.JS
This file contains 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 QBuffer = exports.QBuffer= function(){ | |
this.list = [] | |
this.length = 0 | |
} | |
QBuffer.prototype.append=function(chunk){ | |
this.list.push(chunk) | |
this.length += chunk.length | |
} | |
QBuffer.prototype.read=function(N){ | |
var M = (N<this.length)? N: this.length | |
var result = new Buffer(M) | |
var read_count = 0 | |
while(this.list.length>0){ | |
if(read_count == M) break; | |
var chunk = this.list[0] | |
if(chunk.length <= M - read_count){ | |
chunk.copy(result,read_count,0,chunk.length) | |
read_count += chunk.length | |
this.list.shift() | |
}else{ | |
need_count = M - read_count | |
chunk.copy(result,read_count,0,need_count) | |
this.list[0] = this.list[0].slice(need_count) | |
break; | |
} | |
} | |
this.length -= M | |
return result | |
} | |
QBuffer.prototype.search=function(niddle){ | |
if(typeof niddle == 'string') | |
niddle = new Buffer(niddle) | |
var i=0 | |
var j=0 | |
var k=0 | |
var last_i=0 | |
var last_j=0 | |
var found=false | |
var offset = 0 | |
while(true){ | |
if(i>=this.list.length)break; | |
if(j>=this.list[i].length)break; | |
var c = this.list[i][j] | |
if(c == niddle[k]){ | |
if(j<this.list[i].length-1) | |
j++ | |
else{ | |
i++ | |
j=0 | |
} | |
k++ | |
if(k==niddle.length){ | |
found = true | |
break | |
} | |
}else{ | |
k = 0 | |
i = last_i | |
j = last_j | |
if(j<this.list[i].length-1) | |
j++ | |
else{ | |
i++ | |
j=0 | |
} | |
last_i = i | |
last_j = j | |
offset++ | |
} | |
} | |
if(found) | |
return offset | |
else | |
return -1 | |
} | |
QBuffer.prototype.readUntil=function(niddle){ | |
if(typeof niddle == 'string') | |
niddle = new Buffer(niddle) | |
var offset = this.search(niddle) | |
if(offset!=-1) | |
return this.read(offset) | |
else | |
return new Buffer(0) | |
} | |
QBuffer.prototype.readUntilOrEnd=function(niddle){ | |
if(typeof niddle == 'string') | |
niddle = new Buffer(niddle) | |
var offset = this.search(niddle) | |
if(offset!=-1) | |
return this.read(offset) | |
else | |
return this.read(this.length) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
var QBuffer = require('./qbuffer').QBuffer
var fs = require('fs')
var buf = new QBuffer()
var myfile=fs.createReadStream("hugefile.txt")
myfile.on('data',function(data){
buf.append(data)
var line = null
line = buf.readUntil("\r\n")
if(line.length>0){
console.log(line.toString())
buf.read(2) //skip two bytes of CRLF
}
})
myfile.on('end',function(){
while(buf.length>0){
console.log(buf.readUntilOrEnd("\r\n").toString())
buf.read(2) //skip two bytes of CRLF
}
})