UNPKG

2.27 kBJavaScriptView Raw
1var util = require('util'),
2 fs = require('fs'),
3 Buffer = require('buffer').Buffer;
4
5var FileWindow = exports.FileWindow = function(idxfile, version) {
6 var _idxfile = idxfile, _version = version, _global_offset, _offset = null, _seek_offset = 0;
7 // Set file global offset
8 _global_offset = _version == 2 ? 8 : 0;
9 //Internal properties
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
17FileWindow.prototype.unmap = function() {
18 this.idxfile = null;
19}
20
21FileWindow.prototype.index = function(idx) {
22 var offset = null, len = null, seek_offset = null;
23 // open the file
24 var idx_handle = fs.openSync(this.idxfile, "r");
25
26 if(idx.length == 1) idx = idx[0];
27 // Number support
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 // Seek position equivalent using a position in the read
39 if(this.offset != offset) {
40 this.seek_offset = offset + this.global_offset;
41 }
42
43 // Adjust the stored offset
44 this.offset = (offset + len) ? len : 1;
45 if(!len) len = 1;
46
47 // Read the offset value
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 // Update seek_offset
56 this.seek_offset = this.seek_offset + len;
57
58 // Close the file don't keep file handles around
59 fs.closeSync(idx_handle);
60 return buffer;
61}
62
63FileWindow.prototype.close = function() {
64 // fs.closeSync(this.idxfile);
65 this.unmap();
66}
\No newline at end of file