Passed
Pull Request — main (#2)
by Ilya
01:56
created

file_bytes_reader.js ➔ getLength   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
1
/** global: fileBytesReader */
2
/** global: FileReader */
3
4
/**
5
 * read file as string, bytes (uint8Array), int (1 byte)
6
 *
7
 *
8
 * @return The fileBytesReader object.
9
 *
10
 * @static
11
 *
12
 * @example
13
 *     var fileElement = document.getElementById('file').files[0];
14
 *     var file = fileBytesReader(fileElement);
15
 *
16
 * @param file a fileElement object
17
 */
18
19
20
const fileBytesReader = function(file) {
1 ignored issue
show
Unused Code introduced by
The constant fileBytesReader seems to be never used. Consider removing it.
Loading history...
21
    let _i = 0;
22
    let _fileSize = file.size;
23
    let _reader = new FileReader();
24
    let _file = file;
25
26
    function readChunk(length) {
27
        return new Promise((resolve, reject) => {
28
            let blob = _file.slice(_i, _i += length);
29
30
            _reader.onload = () => {
31
                // return Uint8Array
32
                resolve(new Uint8Array(_reader.result));
33
            };
34
35
            _reader.onerror = reject;
36
37
            _reader.readAsArrayBuffer(blob);
38
        });
39
    }
40
41
    async function readBytes(length) {
42
        return await readChunk(length);
43
    }
44
45
    async function readByte() {
46
        let bytes = await readBytes(1);
47
        return bytes[0];
48
    }
49
50
    function getCurrentPosition() {
51
        return _i;
52
    }
53
54
    function getLength() {
55
        return _fileSize;
56
    }
57
58
    return {
59
        readByte: readByte,
60
        readBytes: readBytes,
61
        getCurrentPosition: getCurrentPosition,
62
        getLength: getLength,
63
    };
64
};
65