1 | var util = require('util'),
|
2 | fs = require('fs'),
|
3 | Buffer = require('buffer').Buffer;
|
4 |
|
5 | var FileWindow = exports.FileWindow = function(idxfile, version) {
|
6 | var _idxfile = idxfile, _version = version, _global_offset, _offset = null, _seek_offset = 0;
|
7 |
|
8 | _global_offset = _version == 2 ? 8 : 0;
|
9 |
|
10 | Object.defineProperty(this, "idxfile", { get: function() { return _idxfile; }, set: function(value) { _idxfile = value; }, enumerable: true});
|
11 | Object.defineProperty(this, "version", { get: function() { return _version; }, enumerable: true});
|
12 | Object.defineProperty(this, "global_offset", { get: function() { return _global_offset; }, enumerable: true});
|
13 | Object.defineProperty(this, "offset", { get: function() { return _offset; }, set: function(value) { _offset = value; }, enumerable: true});
|
14 | Object.defineProperty(this, "seek_offset", { get: function() { return _seek_offset; }, set: function(value) { _seek_offset = value; }, enumerable: true});
|
15 | }
|
16 |
|
17 | FileWindow.prototype.unmap = function() {
|
18 | this.idxfile = null;
|
19 | }
|
20 |
|
21 | FileWindow.prototype.index = function(idx) {
|
22 | var offset = null, len = null, seek_offset = null;
|
23 |
|
24 | var idx_handle = fs.openSync(this.idxfile, "r");
|
25 |
|
26 | if(idx.length == 1) idx = idx[0];
|
27 |
|
28 | if(idx.constructor == Number && idx === parseInt(value, 10)) {
|
29 | offset = idx;
|
30 | len = null;
|
31 | } else if(Array.isArray(idx)) {
|
32 | offset = idx[0];
|
33 | len = idx[1]
|
34 | } else {
|
35 | throw "invalid index param: " + util.inspect(idx);
|
36 | }
|
37 |
|
38 |
|
39 | if(this.offset != offset) {
|
40 | this.seek_offset = offset + this.global_offset;
|
41 | }
|
42 |
|
43 |
|
44 | this.offset = (offset + len) ? len : 1;
|
45 | if(!len) len = 1;
|
46 |
|
47 |
|
48 | var buffer = new Buffer(len);
|
49 |
|
50 | if(len) {
|
51 | fs.readSync(idx_handle, buffer, 0, len, this.seek_offset);
|
52 | } else {
|
53 | fs.readSync(idx_handle, buffer, 0, 1, this.seek_offset);
|
54 | }
|
55 |
|
56 | this.seek_offset = this.seek_offset + len;
|
57 |
|
58 |
|
59 | fs.closeSync(idx_handle);
|
60 | return buffer;
|
61 | }
|
62 |
|
63 | FileWindow.prototype.close = function() {
|
64 |
|
65 | this.unmap();
|
66 | } |
\ | No newline at end of file |