Search code examples
javascriptnode.jsstringblobbuffer

Nodejs: Converting a blob to baser64 & back again in blob are of different size


I'm using this in a Node.js app. I have a blob which I'm converting to a base64 string & back to a blob as below:

// Converting Blob to base64 string via Buffer
const buffer = Buffer.from(await myBlob.text(), 'binary');
console.log(buffer);
const res = buffer.toString('base64');
console.log(res);

// Converting base64 string back to Blob via Buffer
const blob = new Blob([Buffer.from(res, 'base64')],  { type: 'application/octet-stream' });
console.log(blob);
console.log(await blob.text());

The console outputs for both are different:

Blob { size: 32, type: 'application/octet-stream' }
�{fF�d�{3T!�7���X��
<Buffer 50 3c fd fd fd 05 1a 35 38 6b 0d fd 02 7b 66 46 fd 64 fd 7b 33 54 21 fd 37 fd fd fd 58 fd fd>
UDz9/f0FGjU4aw39AntmRv1k/XszVCH9N/39/Vj9/Q==
Blob { size: 31, type: 'application/octet-stream' }
�{fF�d�{3T!�7���X��

Everytime I run the above code snippet the size of the final blob changes. But note that the await blob.text() results always match for the two.

I want the exact same blob as I started with. How can I get that back?


Solution

  • This is how I solved this problem:

    const buffer = await myBlob.arrayBuffer();
    const bufferJson = Buffer.from(buffer).toJSON(); // I eventually want a JSON as I want to pint this to IPFS
    
    const blob = new Blob([Buffer.from(bufferJson)], { type: 'application/octet-stream' }); // Gives back the original blob