In Node.js you don't have Blobs but Buffers. You can create a buffer from a base64 string like this:

var str = "iAAANS....SUVORK5CYII="; // <-- use real base64 string here
var buf = Buffer.from(str, "base64");

stream.write(buf);
Answer from Marc on Stack Overflow
🌐
Yottabrain
yottabrain.org › blog › javascript › how-to-convert-string-to-blob
How to Convert String to Blob | YottaBrain
December 23, 2022 - NodeJS · JavaScript · less than a minute · The simplest way is to use the Blob constructor. To convert a string to Blob · const str = 'hello world'; const blob = new Blob([str], { type : 'plain/text' }); To convert a JSON to Blob · const obj = { hello: 'world' }; const blob = new ...
Discussions

node.js - How to convert a string to blob/longblob in nodejs - MySQL - Stack Overflow
I am doing a REST API with Node.js - Express and I have to store in a database an image. The type that I have to use for that is longblob. The client send me the image as a String, is there a way to More on stackoverflow.com
🌐 stackoverflow.com
Javascript convert a Blob object to a string and back - Stack Overflow
I have to send a Blob as a String and convert it back to an Blob. The method blob.text() returns a promise with it's content as a String. But how can i convert this string back to a blob? I want to More on stackoverflow.com
🌐 stackoverflow.com
node.js - Conversion of buffer data to blob in NodeJS - Stack Overflow
I get Buffer Data from a storage like for instance. I needed to convert it into a blob. But when i tried doing a toString() to get encoded text just lik... More on stackoverflow.com
🌐 stackoverflow.com
html - Javascript - I created a blob from a string, how do I get the string back out? - Stack Overflow
The 2026 Annual Developer Survey is live— take the Survey today! pythonjavascriptc#reactjsjavaandroidhtmlflutterc++node.jstypescriptcssrphpangularnext.jsspring-bootmachine-learningsqlexceliosazuredocker More on stackoverflow.com
🌐 stackoverflow.com
🌐
Node.js
nodejs.org › api › buffer.html
Buffer | Node.js v26.10.0 Documentation
Creates a new Blob object containing ... the 'Blob' and can therefore be safely modified after the 'Blob' is created. String sources are encoded as UTF-8 byte sequences and copied into the Blob......
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Blob
Blob - Web APIs - MDN Web Docs
3 weeks ago - Returns a promise that resolves with a string containing the entire contents of the Blob interpreted as UTF-8 text. ... Returns a ReadableStream that can be used to read the contents of the Blob in chunks of UTF-8. The Blob() constructor can create blobs from other objects. For example, to ...
🌐
Bun
bun.sh › streams › convert a node.js readable to a blob
Convert a Node.js Readable to a Blob - Bun
July 25, 2026 - To convert a Node.js Readable stream to a Blob in Bun, create a Response with the stream as the body, then call response.blob().
🌐
Bun
bun.com › guides › streams › readable to blob
Convert a Node.js Readable to a Blob | Bun Guides
To convert a Node.js Readable stream to a Blob in Bun, create a Response with the stream as the body, then call response.blob().
🌐
npm
npmjs.com › package › blob-util
blob-util - npm
May 21, 2018 - Convert a binary string to a Blob.
      » npm install blob-util
    
Published: May 21, 2018
Version: 2.0.2
🌐
Stack Overflow
stackoverflow.com › questions › 67780251 › how-to-convert-a-string-to-blob-longblob-in-nodejs-mysql
node.js - How to convert a string to blob/longblob in nodejs - MySQL - Stack Overflow
router.post("/usuario/nuevoPostulante", (req, res) => { const { documento, nombre, direccion, myblob, correo, nacionalidad } = req.body; const query = `CALL add_postulante(?, ?, ?, ?, ?, ?);`; mysqlConnect.query( query, [documento, nombre, direccion, myblob, correo, nacionalidad], (err, rows, fields) => { if (!err) { res.json({ code: 201, data: {}, message: "Se registra correctamente al usuario.", }); } else { console.log(err); res.json({ code: 409, data: {}, message: "Error en la creacion del usuario", }); } } ); }); ... Depending on the format of the base64 string, you might need to prepend content type data.
Find elsewhere
🌐
GitHub
gist.github.com › jdnichollsc › 78a6eb093731cf3e8dfd536dbe4befb3
Convert to Blob with Javascript - Gist - GitHub
dataURLtoBlob.js · 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 · Show hidden characters · Copy link · Copy Markdown · Real source: https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript ·
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Blob › text
Blob: text() method - Web APIs - MDN Web Docs
March 11, 2024 - The text() method of the Blob interface returns a Promise that resolves with a string containing the contents of the blob, interpreted as UTF-8.
Top answer
1 of 1
59

If you're here to convert a Node.js Buffer to a JavaScript Blob:

First of all, Node.js didn't have the Blob class until versions v15.7.0 and v14.18.0, so you need to import the Blob class if you haven't already:

// NOTE: starting from Node.js v18.0.0, the following code is not necessary anymore

// CJS style
const { Blob } = require("buffer");

// ESM style
import { Blob } from "buffer";

NOTE: it appears that in Node.js v14/v15/v16/v17 (last checked: as of v14.19.2, v15.14.0, v16.14.2 and v17.9.0), the Blob class is marked as experimental and not stable. Instead, in Node.js v18.x.x the Blob class is marked as stable.

UPDATE 2022-04-25: starting with Node.js version 18.0.0, you don't have to manually import the Blob class anymore, but you can use it straight away in your code!

Once the Blob class is available, the conversion itself is pretty simple:

const buff = Buffer.from([1, 2, 3]); // Node.js Buffer
const blob = new Blob([buff]); // JavaScript Blob

Old answer about how to transfer a Node.js Buffer via JSON:

If you need to transfer a buffer of data through JSON, you can encode the buffer using a text-based encoding like hexadecimal or base64.

For instance:

// get the buffer from somewhere
const buff = fs.readFileSync("./test.bin");
// create a JSON string that contains the data in the property "blob"
const json = JSON.stringify({ blob: buff.toString("base64") });

// on another computer:
// retrieve the JSON string somehow
const json = getJsonString();
const parsed = JSON.parse(json);
// retrieve the original buffer of data
const buff = Buffer.from(parsed.blob, "base64");
🌐
Coderanch
coderanch.com › t › 661628 › languages › Converting-String-Blob
Converting a String in a Blob (HTML Pages with CSS and JavaScript forum at Coderanch)
It's intended to read from a file for blob. [Asking smart questions] [About Bear] [Books by Bear] ... Dear Bear Bibeault, yes, I understand the parameter must be a blob not a string. But in my program I receive a string not a blob. So, my question is; How convert a String to a blob?
🌐
Microsoft Learn
learn.microsoft.com › en-us › azure › storage › blobs › storage-quickstart-blobs-nodejs
Quickstart: Azure Blob Storage client library for Node.js
September 13, 2024 - Find the <storage-account-name> placeholder and replace it with the actual name of the storage account created by the azd up command. Save the changes. Run the project: Execute the following command to run the app: ... Observe the output: This ...
🌐
GitHub
github.com › hgourvest › node-firebird › issues › 82
BLOB Texts to string on NodeJS · Issue #82 · hgourvest/node-firebird
October 19, 2015 - When I am running the code below, it gives me [Error: invalid BLOB ID]. Any suggestions · Note: BLOBs are Blob sub_type 1
Author: hgourvest
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
Top answer
1 of 16
1181

The atob function will decode a base64-encoded string into a new string with a character for each byte of the binary data.

const byteCharacters = atob(b64Data);

Each character's code point (charCode) will be the value of the byte. We can create an array of byte values by applying this using the .charCodeAt method for each character in the string.

const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}

You can convert this array of byte values into a real typed byte array by passing it to the Uint8Array constructor.

const byteArray = new Uint8Array(byteNumbers);

This in turn can be converted to a Blob by wrapping it in an array and passing it to the Blob constructor.

const blob = new Blob([byteArray], {type: contentType});

The code above works. However the performance can be improved a little by processing the byteCharacters in smaller slices, rather than all at once. In my rough testing 512 bytes seems to be a good slice size. This gives us the following function.

const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }
    
  const blob = new Blob(byteArrays, {type: contentType});
  return blob;
}
const blob = b64toBlob(b64Data, contentType);
const blobUrl = URL.createObjectURL(blob);

window.location = blobUrl;

Full Example:

Show code snippet

const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }
    
  const blob = new Blob(byteArrays, {type: contentType});
  return blob;
}

const contentType = 'image/png';
const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';

const blob = b64toBlob(b64Data, contentType);
const blobUrl = URL.createObjectURL(blob);

const img = document.createElement('img');
img.src = blobUrl;
document.body.appendChild(img);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 16
666

Here is a more minimal method without any dependencies or libraries.
It requires the new fetch API. (Can I use it?)

var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

fetch(url)
.then(res => res.blob())
.then(console.log)
Run code snippetEdit code snippet Hide Results Copy to answer Expand

With this method you can also easily get a ReadableStream, ArrayBuffer, text, and JSON.
(fyi this also works with node-fetch in Node)

As a function:

const b64toBlob = (base64, type = 'application/octet-stream') => 
  fetch(`data:${type};base64,${base64}`).then(res => res.blob())

But I would encourage you to don't use base64 in the first place. There are better ways to send and receive binary data. JSON isn't always the best option. it takes up more bandwidth and waste processing time (de)encodeing stuff. Us eg canvas.toBlob instead of canvas.toDataURL and use FormData to send binary files. you can also return back a multipart payload and decode it using await response.formData() that is coming from a server response. FormData can go both ways.


I did a simple performance test towards Jeremy's ES6 sync version.
The sync version will block UI for a while. keeping the devtool open can slow the fetch performance

Show code snippet

document.body.innerHTML += '<input autofocus placeholder="try writing">'
// get some dummy gradient image
var img=function(){var a=document.createElement("canvas"),b=a.getContext("2d"),c=b.createLinearGradient(0,0,1500,1500);a.width=a.height=3000;c.addColorStop(0,"red");c.addColorStop(1,"blue");b.fillStyle=c;b.fillRect(0,0,a.width,a.height);return a.toDataURL()}();


async function perf() {
  
  const blob = await fetch(img).then(res => res.blob())
  // turn it to a dataURI
  const url = img
  const b64Data = url.split(',')[1]

  // Jeremy Banks solution
  const b64toBlob = (b64Data, contentType = '', sliceSize=512) => {
    const byteCharacters = atob(b64Data);
    const byteArrays = [];
    
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
      const slice = byteCharacters.slice(offset, offset + sliceSize);
      
      const byteNumbers = new Array(slice.length);
      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }
      
      const byteArray = new Uint8Array(byteNumbers);
      
      byteArrays.push(byteArray);
    }
    
    const blob = new Blob(byteArrays, {type: contentType});
    return blob;
  }

  // bench blocking method
  let i = 500
  console.time('blocking b64')
  while (i--) {
    await b64toBlob(b64Data)
  }
  console.timeEnd('blocking b64')
  
  // bench non blocking
  i = 500

  // so that the function is not reconstructed each time
  const toBlob = res => res.blob()
  console.time('fetch')
  while (i--) {
    await fetch(url).then(toBlob)
  }
  console.timeEnd('fetch')
  console.log('done')
}

perf()
Run code snippetEdit code snippet Hide Results Copy to answer Expand

🌐
JavaScript.info
javascript.info › tutorial › binary data, files
Blob
Help to translate the content of this tutorial to your language! ... ArrayBuffer and views are a part of ECMA standard, a part of JavaScript. In the browser, there are additional higher-level objects, described in File API, in particular Blob. Blob consists of an optional string type (a MIME-type usually), plus blobParts – a sequence of other Blob objects, strings and BufferSource.
🌐
JavaScripture
javascripture.com › Blob
Blob JavaScript API
Creates a new Blob with size set to 0. ... Creates a new Blob. The elements of blobParts must be of the types ArrayBuffer, ArrayBufferView, Blob, or String.