Skip to content

Commit

Permalink
FileReader#readAsArrayBuffer (facebook#36332)
Browse files Browse the repository at this point in the history
Summary:
Fixes a number of issues with third party libraries that use `Blob#arrayBuffer` or `FileReader#readAsArrayBuffer`, including facebook#30769 facebook#34402 facebook#20091 facebook#21209

## Changelog

[INTERNAL] [FIXED] - Implemented FileReader#readAsArrayBuffer

Pull Request resolved: facebook#36332

Test Plan: Added a test which fails against current release but passes after code changes.

Reviewed By: christophpurrer

Differential Revision: D43907171

Pulled By: javache

fbshipit-source-id: 73d622ec569a282b6394732b9a0dc687b447fb62
  • Loading branch information
SheetJSDev authored and OlimpiaZurek committed May 22, 2023
1 parent d5edc78 commit ee379aa
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
32 changes: 30 additions & 2 deletions Libraries/Blob/FileReader.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import type Blob from './Blob';

import NativeFileReaderModule from './NativeFileReaderModule';
import {toByteArray} from 'base64-js';

const EventTarget = require('event-target-shim');

Expand Down Expand Up @@ -74,8 +75,35 @@ class FileReader extends (EventTarget(...READER_EVENTS): any) {
}
}

readAsArrayBuffer(): any {
throw new Error('FileReader.readAsArrayBuffer is not implemented');
readAsArrayBuffer(blob: ?Blob): void {
this._aborted = false;

if (blob == null) {
throw new TypeError(
"Failed to execute 'readAsArrayBuffer' on 'FileReader': parameter 1 is not of type 'Blob'",
);
}

NativeFileReaderModule.readAsDataURL(blob.data).then(
(text: string) => {
if (this._aborted) {
return;
}

const base64 = text.split(',')[1];
const typedArray = toByteArray(base64);

this._result = typedArray.buffer;
this._setReadyState(DONE);
},
error => {
if (this._aborted) {
return;
}
this._error = error;
this._setReadyState(DONE);
},
);
}

readAsDataURL(blob: ?Blob): void {
Expand Down
12 changes: 12 additions & 0 deletions Libraries/Blob/__tests__/FileReader-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,16 @@ describe('FileReader', function () {
});
expect(e.target.result).toBe('data:text/plain;base64,NDI=');
});

it('should read blob as ArrayBuffer', async () => {
const e = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = resolve;
reader.onerror = reject;
reader.readAsArrayBuffer(new Blob());
});
const ab = e.target.result;
expect(ab.byteLength).toBe(2);
expect(new TextDecoder().decode(ab)).toBe('42');
});
});

0 comments on commit ee379aa

Please sign in to comment.