UNPKG

read-excel-file

Version:

Read `.xlsx` files in a web browser or in Node.js

63 lines (59 loc) 2.44 kB
// This code was originally submitted by Etienne Prothon. // https://gitlab.com/catamphetamine/read-excel-file/-/merge_requests/11 // ZIP local file header signature: "PK\x03\x04". The first two bytes "PK" are // shared by every ZIP variant (including the empty-archive `PK\x05\x06` and the // spanned `PK\x07\x08` markers), so matching just "PK" up front avoids rejecting // any valid — if unusual — archive; anything malformed past that point is still // caught by the actual unzipper. var ZIP_FILE_SIGNATURE = [0x50, 0x4B]; // The first four bytes of the OLE2 Compound File Binary format (`0xD0 0xCF 0x11 0xE0`), // which is the container of legacy binary `.xls` files. var XLS_FILE_SIGNATURE = [0xD0, 0xCF, 0x11, 0xE0]; var FILE_TYPE_SIGNATURES = [ZIP_FILE_SIGNATURE, XLS_FILE_SIGNATURE]; // File type "enum". export var XLSX_FILE_TYPE = FILE_TYPE_SIGNATURES.indexOf(ZIP_FILE_SIGNATURE); export var XLS_FILE_TYPE = FILE_TYPE_SIGNATURES.indexOf(XLS_FILE_SIGNATURE); /** * Creates a function get determines a file type based on the leading bytes. * @return {function} A function that receives a `byte` (an element of a `Uint8Array`) and returns a `type: number?` — an index in the file types "enum", or `-1` if it doesn't match any file type, or `undefined` if it's still deciding on the file type. * @throws {InvalidInputError} */ export default function createFileTypeDetector() { var type; var possibleTypes = indexesOf(FILE_TYPE_SIGNATURES); var i = 0; // Returns a function that should be called for each leading byte of the file // until it starts returning a number. return function (_byte) { // If the type of the file is still being determined. if (isNaN(type)) { var t; possibleTypes = possibleTypes.filter(function (typeIndex) { if (_byte === FILE_TYPE_SIGNATURES[typeIndex][i]) { if (FILE_TYPE_SIGNATURES[typeIndex].length === i + 1) { t = typeIndex; } return true; } }); if (possibleTypes.length === 1) { type = t; } else if (possibleTypes.length === 0) { // `type: -1` means "the type of the file couldn't be determined" type = -1; } } i++; return type; }; } function indexesOf(array) { var indexes = []; var i = 0; while (i < array.length) { indexes.push(i); i++; } return indexes; } //# sourceMappingURL=createFileTypeDetector.js.map