ReferenceError: Blob is not defined in JavaScript [Solved]

avatar
Borislav Hadzhiev

Last updated: Mar 2, 2024
2 min

banner

# ReferenceError: Blob is not defined in JavaScript

The "Blob is not defined" error occurs when the Blob class is used without being imported into 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, 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: '' }

import and use blob class from buffer module

The code for this article is available on GitHub

The Blob class takes 2 parameters:

  1. sources - an array to 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). The Content-Type of the Blob can also be set 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 where 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.

Note that Blob is a globally available class in Node.js starting with version 18.

You can check your version of Node with the node -v command.

shell
node -v

If you use Node.js version 18+, you can directly use the Blob class without importing it.

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

# Using the cross-blob module instead

An alternative to using the built-in Blob class is to use the cross-blob npm module.

The module offers cross-platform blob implementation for Node.js and the Web.

You can install cross-blob by running the following command.

shell
# ๐Ÿ‘‡๏ธ with NPM npm install cross-blob # ๐Ÿ‘‡๏ธ with YARN yarn add cross-blob

npm install cross blob

Now you can import the Blob class from the package as follows.

index.js
import Blob from 'cross-blob'; const blob = new Blob(['hello world']); console.log(blob.size); // ๐Ÿ‘‰๏ธ 11 // Global patch (to support external modules like is-blob). globalThis.Blob = Blob;

import and use cross blob module

javascript-referenceerror-blob-is-not-defined

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev