Solve - ReferenceError Blob is not defined in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20211 min read

banner

Photo by Megan Nixon

Solve - Blob is not defined Error in JavaScript #

The "Blob is not defined" error occurs when the Blob class is used without being imported in a Node.js application. To solve the error import the Blob class before using it, e.g. import { Blob } from 'buffer';.

referenceerror blob is not defined

To solve the error, we have to import the Blob class before using it.

index.js
import {Blob} from 'buffer'; const blob = new Blob(['hello world']); console.log(blob); // ๐Ÿ‘‰๏ธ Blob { size: 11, type: '' }

The Blob class takes 2 parameters:

  1. sources - an array that will be stored within the Blob
  2. options - an object, where we can set the endings to transparent or native (line endings get converted to the platform native line endings). We can also set the content-type of the Blob in the object.
The Blob constructor creates and returns a new Blob object that contains the concatenation of the provided sources.

You can modify the sources after the Blob is created.

Here's an example were we explicitly set the content-type of the Blob.

index.js
import {Blob} from 'buffer'; const obj = {name: 'James Doe'}; const blob = new Blob([JSON.stringify(obj, null, 2)], { type: 'application/json', }); console.log(blob); // ๐Ÿ‘‰๏ธ Blob { size: 25, type: 'application/json' }

We constructed a Blob from a JSON string and set its content-type to application/json.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee