forked from davidbenhaim/FileLineReader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
82 lines (64 loc) · 1.92 KB
/
index.js
File metadata and controls
82 lines (64 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//
// Module: LineBufferReader
// Constructor: FileLineReader(filename, bufferSize = 8192)
// Methods: hasNextLine() -> boolean
// nextLine() -> String
// Author(s): Originaly by Dirk Jäckel (http://blog.jaeckel.com/2010/03/i-tried-to-find-example-on-using-node.html)
// NPMified by David Benhaim (github.com/davidbenhaim)
//
var fs = require("fs");
var sys = require("sys");
module.exports = function(filename, bufferSize) {
if(!bufferSize || bufferSize <= 0) {
bufferSize = 8192;
}
//private:
var currentPositionInFile = 0;
var buffer = "";
var fd = fs.openSync(filename, "r");
// return -1
// when EOF reached
// fills buffer with next 8192 or less bytes
var fillBuffer = function(position) {
var res = fs.readSync(fd, bufferSize, position, "ascii");
buffer += res[0];
if (res[1] == 0) {
return -1;
}
return position + res[1];
};
currentPositionInFile = fillBuffer(0);
//public:
this.hasNextLine = function() {
while (buffer.indexOf("\n") == -1 && currentPositionInFile != -1) {
currentPositionInFile = fillBuffer(currentPositionInFile);
if (currentPositionInFile == -1) {
break;
// return false;
}
}
if (buffer.indexOf("\n") > -1 || buffer.length > 0) {
return true;
}
return false;
};
//public:
this.bufferSize = function(){
return buffer.length
};
//public:
this.nextLine = function() {
var lineEnd = buffer.indexOf("\n");
if(lineEnd == -1){
lineEnd = buffer.length;
}
var result = buffer.substring(0, lineEnd);
buffer = buffer.substring(result.length + 1, buffer.length);
return result;
};
//public
this.close = function() {
fs.closeSync(fd);
};
return this;
};