UNPKG

typesxml

Version:

Open source XML library written in TypeScript

92 lines 3.26 kB
"use strict"; /******************************************************************************* * Copyright (c) 2023 - 2024 Maxprograms. * * This program and the accompanying materials * are made available under the terms of the Eclipse License 1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/org/documents/epl-v10.html * * Contributors: * Maxprograms - initial API and implementation *******************************************************************************/ Object.defineProperty(exports, "__esModule", { value: true }); exports.FileReader = void 0; const fs_1 = require("fs"); class FileReader { fileHandle; encoding; blockSize; fileSize; position; firstRead; constructor(path, encoding) { let stats = (0, fs_1.statSync)(path, { bigint: false, throwIfNoEntry: true }); this.fileSize = stats.size; this.blockSize = stats.blksize; this.fileHandle = (0, fs_1.openSync)(path, 'r'); if (encoding) { this.encoding = encoding; } else { this.encoding = FileReader.detectEncoding(path); } this.position = 0; this.firstRead = true; } static detectEncoding(path) { const fd = (0, fs_1.openSync)(path, 'r'); let buffer = Buffer.alloc(3); let bytesRead = (0, fs_1.readSync)(fd, buffer, 0, 3, 0); (0, fs_1.closeSync)(fd); if (bytesRead < 3) { throw new Error('Error reading BOM: not enough bytes'); } const UTF8 = Buffer.from([-17, -69, -65]); const UTF16 = Buffer.from([-2, -1]); if (buffer.toString().startsWith(UTF8.toString())) { return 'utf8'; } if (buffer.toString().startsWith(UTF16.toString())) { return 'utf16le'; } return 'utf8'; } getEncoding() { return this.encoding; } setEncoding(encoding) { this.encoding = encoding; } read() { let buffer = Buffer.alloc(this.blockSize, this.encoding); let amount = this.blockSize <= this.fileSize - this.position ? this.blockSize : this.fileSize - this.position; let bytesRead = (0, fs_1.readSync)(this.fileHandle, buffer, 0, amount, this.position); this.position += bytesRead; return this.firstRead ? this.skipBOM(buffer, bytesRead) : buffer.toString(this.encoding, 0, bytesRead); } skipBOM(buffer, bytesRead) { this.firstRead = false; const utf8Bom = Buffer.from([-17, -69, -65]).toString(); const utf16Bom = Buffer.from([-2, -1]).toString(); let result = buffer.toString(this.encoding, 0, bytesRead); if (result.startsWith(utf8Bom)) { return result.substring(utf8Bom.length); } if (result.startsWith(utf16Bom)) { return result.substring(utf16Bom.length); } return buffer.toString(this.encoding, 0, bytesRead); } dataAvailable() { return this.position < this.fileSize; } getFileSize() { return this.fileSize; } closeFile() { (0, fs_1.closeSync)(this.fileHandle); } } exports.FileReader = FileReader; //# sourceMappingURL=FileReader.js.map