Passed
Push — async ( 76f42a...eb4889 )
by Ilya
01:16
created

file_bytes_reader.js ➔ readBytes   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
/**
2
 * read file as string, bytes (uint8Array), int (1 byte)
3
 *
4
 *
5
 * @return The fileBytesReader object.
6
 *
7
 * @static
8
 *
9
 * @example
10
 *     var fileElement = document.getElementById('file').files[0];
11
 *     var file = fileBytesReader(fileElement);
12
 *
13
 * @param file a fileElement object
14
 */
15
16
17
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...
18
    let _i = 0;
19
    let _fileSize = file.size;
20
    let _reader = new FileReader();
0 ignored issues
show
Bug introduced by
The variable FileReader seems to be never declared. If this is a global, consider adding a /** global: FileReader */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
21
    let _file = file;
22
23
    function readChunk(length) {
24
        return new Promise((resolve, reject) => {
25
            let blob = _file.slice(_i, _i += length);
26
27
            _reader.onload = () => {
28
                // return Uint8Array
29
                resolve(new Uint8Array(_reader.result));
30
            };
31
32
            _reader.onerror = reject;
33
34
            _reader.readAsArrayBuffer(blob);
35
        });
36
    }
37
38
    async function readBytes(length) {
39
        return await readChunk(length);
40
    }
41
42
    async function readByte() {
43
        let bytes = await readBytes(1);
44
        return bytes[0];
45
    }
46
47
    function getCurrentPosition() {
48
        return _i;
49
    }
50
51
    function getLength() {
52
        return _fileSize;
53
    }
54
55
    return {
56
        readByte: readByte,
57
        readBytes: readBytes,
58
        getCurrentPosition: getCurrentPosition,
59
        getLength: getLength,
60
    };
61
};
62