Skip to content

Instantly share code, notes, and snippets.

@shazron
Created October 30, 2023 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shazron/d1144b52fa3cc8326fbceb269820f1c7 to your computer and use it in GitHub Desktop.
Save shazron/d1144b52fa3cc8326fbceb269820f1c7 to your computer and use it in GitHub Desktop.
blob2buffer and buffer2blob
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