A LineReader, because this kind of stuff should just exist already. ;P
This commit is contained in:
parent
2aa050b815
commit
5476c463c8
3 changed files with 57 additions and 14 deletions
|
|
@ -187,3 +187,40 @@ exports.copyDirRecursive = function copyDirRecursive(srcDir, newDir, clbk) {
|
|||
});
|
||||
});
|
||||
};
|
||||
|
||||
exports.LineReader = function(filename, bufferSize) {
|
||||
this.bufferSize = bufferSize || 8192;
|
||||
this.buffer = "";
|
||||
this.fd = fs.openSync(filename, "r");
|
||||
this.currentPosition = 0;
|
||||
}
|
||||
|
||||
exports.LineReader.prototype = {
|
||||
getBufferAndSetCurrentPosition: function(position) {
|
||||
var res = fs.readSync(this.fd, this.bufferSize, position, "ascii");
|
||||
|
||||
this.buffer += res[0];
|
||||
if(res[1] === 0) return -1;
|
||||
|
||||
this.currentPosition = position + res[1];
|
||||
return this.currentPosition;
|
||||
},
|
||||
|
||||
hasNextLine: function() {
|
||||
while(this.buffer.indexOf('\n') === -1) {
|
||||
this.getBufferAndSetCurrentPosition(this.currentPosition);
|
||||
if(this.currentPosition === -1) return false;
|
||||
}
|
||||
|
||||
if(this.buffer.indexOf("\n") > -1) return true;
|
||||
return false;
|
||||
},
|
||||
|
||||
getNextLine: function() {
|
||||
var lineEnd = this.buffer.indexOf("\n"),
|
||||
result = this.buffer.substring(0, lineEnd);
|
||||
|
||||
this.buffer = this.buffer.substring(result.length + 1, this.buffer.length);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
|
|
|||
Reference in a new issue