Created
October 30, 2023 01:38
-
-
Save shazron/d1144b52fa3cc8326fbceb269820f1c7 to your computer and use it in GitHub Desktop.
blob2buffer and buffer2blob
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Blob } = require('node:buffer'); | |
/** | |
* Converts a Buffer to a Blob. | |
* | |
* @param {Buffer} buffer the Buffer to convert | |
* @returns {Blob} the converted Buffer as a Blob | |
*/ | |
function buffer2blob(buffer) { | |
if (buffer instanceof Buffer === false) { | |
throw new Error('not an instance of a Buffer') | |
} | |
return new Blob([buffer]) | |
} | |
/** | |
* Converts a Blob to a Buffer. | |
* | |
* @param {Blob} blob the Blob to convert | |
* @returns {Buffer} the converted Blob as a Buffer | |
*/ | |
async function blob2buffer(blob) { | |
if (blob instanceof Blob === false) { | |
throw new Error('not an instance of a Blob') | |
} | |
const arrayBuffer = await blob.arrayBuffer() | |
return Buffer.from(arrayBuffer, 'binary') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment