Last updated: Mar 2, 2024
Reading timeยท2 min
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';
.
To solve the error, import the Blob class before using it.
import {Blob} from 'buffer'; const blob = new Blob(['hello world']); console.log(blob); // ๐๏ธ Blob { size: 11, type: '' }
The Blob
class takes 2 parameters:
Blob
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.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
.
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.
node -v
If you use Node.js version 18+, you can directly use the Blob
class without
importing it.
const blob = new Blob(['hello world']); console.log(blob); // ๐๏ธ Blob { size: 11, type: '' }
cross-blob
module insteadAn 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.
# ๐๏ธ with NPM npm install cross-blob # ๐๏ธ with YARN yarn add cross-blob
Now you can import the Blob
class from the package as follows.
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;
javascript-referenceerror-blob-is-not-defined