UNPKG

beth-parser

Version:

Parser library for Bethesda's Creation Engine data files

85 lines 3.23 kB
"use strict"; exports.__esModule = true; var fs = require("fs"); /** * Node.js based file data source using single internal read buffer. * * When specifying internal buffer size (i.e. not relying on the default value), keep in mind that * every read request that can't fit inside that buffer will result in a new buffer allocation. */ var FileSource = /** @class */ (function () { /** * @param path Source file path. * @param bufferSize Size of the internal source buffer. */ function FileSource(path, bufferSize) { if (bufferSize === void 0) { bufferSize = 0x3fff; } /** * Current read position. */ this.filePosition = 0; /** * Cursor position inside source buffer. */ this.bufferOffset = 0; /** * Actual data length inside source buffer. */ this.bufferLength = 0; this.fileDesc = fs.openSync(path, "r"); this.sourceBuffer = Buffer.alloc(bufferSize || 0x3fff); } /** * Read another portion of the file into the target buffer. */ FileSource.prototype.readFile = function (buffer) { var reminderLength = this.bufferLength - this.bufferOffset; // Copy buffer reminder to the beginning of the target buffer this.sourceBuffer.copy(buffer, 0, this.bufferOffset, this.bufferLength); // Reset read length and position this.bufferLength = 0; this.bufferOffset = 0; // Try to read the rest of the buffer var bytesRead = fs.readSync(this.fileDesc, buffer, reminderLength, buffer.length - reminderLength, this.filePosition); this.filePosition += bytesRead; return buffer.subarray(0, reminderLength + bytesRead); }; /** * Read data using the internal source buffer. */ FileSource.prototype.readBuffer = function (length) { if (this.bufferOffset + length > this.bufferLength) { this.bufferLength = this.readFile(this.sourceBuffer).length; } if (this.bufferOffset + length > this.bufferLength) { length = this.bufferLength; } this.bufferOffset += length; return this.sourceBuffer.subarray(this.bufferOffset - length, this.bufferOffset); }; FileSource.prototype.read = function (length) { if (length > this.sourceBuffer.length) { return this.readFile(Buffer.alloc(length)); } else { return this.readBuffer(length); } }; FileSource.prototype.skip = function (length) { this.bufferOffset += length; if (this.bufferOffset > this.bufferLength) { this.filePosition += this.bufferOffset - this.bufferLength; this.bufferOffset = 0; this.bufferLength = 0; } }; FileSource.prototype.close = function () { fs.closeSync(this.fileDesc); }; FileSource.prototype.cursor = function () { return this.filePosition - this.bufferLength + this.bufferOffset; }; return FileSource; }()); exports["default"] = FileSource; //# sourceMappingURL=FileSource.js.map