What is fetch-blob?
The fetch-blob npm package is a module that allows you to work with Blob data in a way that is consistent with the browser's Fetch API. It provides a way to create, read, and manipulate binary data in Node.js, which can be useful for tasks such as file uploads, image processing, and other operations that involve handling raw binary data.
What are fetch-blob's main functionalities?
Creating a Blob
This feature allows you to create a new Blob object from raw data. The example code creates a Blob containing the text 'Hello, world!' with a MIME type of 'text/plain'.
const { Blob } = require('fetch-blob');
const blob = new Blob(['Hello, world!'], { type: 'text/plain' });
Reading a Blob as text
This feature allows you to read the contents of a Blob as text. The example code reads the text from the Blob and logs it to the console.
const { Blob } = require('fetch-blob');
const blob = new Blob(['Hello, world!'], { type: 'text/plain' });
blob.text().then((text) => {
console.log(text); // Outputs: Hello, world!
});
Reading a Blob as a Buffer
This feature allows you to read the contents of a Blob as an ArrayBuffer, which can then be converted to a Node.js Buffer. The example code demonstrates how to convert the ArrayBuffer to a Buffer and log it to the console.
const { Blob } = require('fetch-blob');
const blob = new Blob(['Hello, world!'], { type: 'text/plain' });
blob.arrayBuffer().then((buffer) => {
const nodeBuffer = Buffer.from(buffer);
console.log(nodeBuffer); // Outputs: <Buffer 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21>
});
Other packages similar to fetch-blob
blob
The 'blob' package is another implementation of the Blob object for Node.js. It is similar to fetch-blob but may have differences in API and supported features.
form-data
The 'form-data' package allows you to create `multipart/form-data` streams that can be used for submitting forms and file uploads in Node.js. It is similar to fetch-blob in that it deals with binary data, but it is more focused on form submission and multipart data.
buffer
The 'buffer' package is a Node.js core module that provides a way to handle binary data. While not a direct alternative to fetch-blob, it is often used in conjunction with other modules to handle binary data in Node.js applications.
fetch-blob
A Blob implementation in Node.js, originally from node-fetch.
Installation
npm install fetch-blob
Usage
const Blob = require('fetch-blob');
const fetch = require('node-fetch');
fetch('https://httpbin.org/post', {
method: 'POST',
body: new Blob(['Hello World'], { type: 'text/plain' })
})
.then(res => res.json());
.then(json => console.log(json));
Blob part backed up by filesystem
To use, install domexception.
npm install fetch-blob domexception
const blobFrom = require('fetch-blob/from.js');
const blob1 = blobFrom('./2-GiB-file.bin');
const blob2 = blobFrom('./2-GiB-file.bin');
const blob = new Blob([blob1, blob2]);
console.log(blob.size)
See the MDN documentation and tests for more details.