Explain Codes LogoExplain Codes Logo

Node.js can't create Blobs?

javascript
blob
buffer
fs
Alex KataevbyAlex Kataev·Mar 1, 2025
TLDR

In Node.js, think Buffer when you need to work with binary data:

// Initiate your Buffer with a classic "Hello, Buffer!" const buffer = Buffer.from('Hello, Buffer!', 'utf-8');

Got some code expecting a Blob? Use the buffer library as a stand-in:

const { Blob } = require('buffer'); // And voila! More blobby than a supermassive black hole! const blob = new Blob([buffer], { type: 'application/octet-stream' });

In the Node.js universe, Buffer reigns supreme. Using Blob from the buffer library helps when your code needs to impersonate browser code.

Blob emulation in pre-Node.js 16

Starting with Node.js 16, we received the Blob support natively. Great news, indeed! However, we still have to sympathize with those stuck in older versions. For them, third-party libraries to the rescue!

const Blob = require('cross-blob'); const blob = new Blob(['Using Blob in Node.js, what a time to be alive!'], { type: 'text/plain' });

Creating a Blob just like we do in the browser, no big deal with cross-blob. Hang on, browser... we're catching up!

Binary data handling with Buffer and fs

Remember, Buffer is Node.js**'s native way of dealing with **binary data**. When it comes to files or streamed data (like **WAV** audio), **Buffer** and the **fs` module go together like bread and butter:

const fs = require('fs'); const buffer = Buffer.from(audioData); fs.writeFile('audio.wav', buffer, (err) => { // What can we do without error handling? if (err) throw err; console.log('Binary audio data saved – music to my ears!'); });

It's that simple! A Willy Wonka golden ticket to Binaryville.

Unit testing victory with Blob

In the trenches of unit testing with Jest, a Blob can feel like a slippery eel. No worries though, we've got the right gear to handle it:

const { Blob } = require('buffer'); test('Blob creation', () => { // Nothing tests faith like a Blob test! const testData = 'Hello, Blob!'; const blob = new Blob([testData], { type: 'text/plain' }); // Further Blob tests here. Keep calm and carry on testing. });

Clipboard between Node.js and browser

If you're working on code meant for both browsers and Node.js, you can't ignore Blob. Thankfully there are polyfills that let Blob feel right at home even in Node.js.

// Meet the polyfill that makes Blob feel at home. globalThis.Blob = require('cross-blob');

Just like that, we can confidently talk about Blob in Node.js and browser alike!

And finally, end your Blob creation by setting the correct MIME type.

const blob = new Blob(['Hello, Blob!'], { type: 'application/json' });