react-native-blob-util icon indicating copy to clipboard operation
react-native-blob-util copied to clipboard

File gets corrupted with readStream() with base64 when using bufferSize defaults

Open sam-maverick opened this issue 2 months ago • 0 comments

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

I had an issue when using readStream() with base64 files when using the default for the bufferSize parameter. The issue was that the file contents were corrupted. At first glance they looked the same, but readStream() was giving me some extra bytes that I didn't know where they were coming from.

The docs state the following,

bufferSize: number (optional) Buffer size of read stream, default to 4096 and 4095(when encoding is base64)

And

when reading file in BASE64 encoding, buffer size must be multiples of 3.

I discovered that the issue is: When you omit the bufferSize argument, the default value is taken from class/ReactNativeBlobUtilReadStream.js, which sets the default to 10240 regardless of the encoding. This value is not good for base64, as it is not a multiple of 3.

Here is the diff that solved my problem:

diff --git a/node_modules/react-native-blob-util/class/ReactNativeBlobUtilReadStream.js b/node_modules/react-native-blob-util/class/ReactNativeBlobUtilReadStream.js
index 490efb1..1256769 100644
--- a/node_modules/react-native-blob-util/class/ReactNativeBlobUtilReadStream.js
+++ b/node_modules/react-native-blob-util/class/ReactNativeBlobUtilReadStream.js
@@ -64,7 +64,7 @@ export default class ReactNativeBlobUtilReadStream {
 
     open() {
         if (!this.closed)
-            ReactNativeBlobUtil.readStream(this.path, this.encoding, this.bufferSize || 10240, this.tick || -1, this.streamId);
+            ReactNativeBlobUtil.readStream(this.path, this.encoding, this.bufferSize || (this.encoding=='base64' ? 4095 : 4096), this.tick || -1, this.streamId);
         else
             throw new Error('Stream closed');
     }

This issue body was partially generated by patch-package.

sam-maverick avatar Apr 09 '24 10:04 sam-maverick