Node.js Blob & File Implementation

4.0.0 · active · verified Sun Apr 19

fetch-blob provides a robust implementation of the Web Blob and File APIs for Node.js environments, originally forked from `node-fetch`. It is currently at stable version 4.0.0, with frequent minor and patch releases, and major releases addressing breaking changes related to internal architecture or standard compliance. Key differentiators include its ability to handle Blob parts backed by the file system without loading content into memory, and its support for WHATWG streams, requiring explicit conversion for Node.js stream compatibility. While Node.js 18+ includes a native `Blob` class, `fetch-blob` remains relevant for older Node.js versions or for its advanced file system-backed blob capabilities.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating a Blob from text, a File from a file path using `fileFromSync`, combining them into a new Blob, and reading its content via a Node.js Readable stream.

import { Blob } from 'fetch-blob';
import { File } from 'fetch-blob/file.js';
import { blobFromSync, fileFromSync } from 'fetch-blob/from.js';
import { Readable } from 'stream';
import { writeFileSync, existsSync, unlinkSync } from 'fs';
import { join } from 'path';

const testFilePath = join(process.cwd(), 'temp-test-file.txt');
writeFileSync(testFilePath, 'This is a test file content.');

async function runQuickstart() {
  // Create a basic Blob from a string
  const textBlob = new Blob(['hello, world', ' and some more text'], { type: 'text/plain' });
  console.log(`Text Blob size: ${textBlob.size} bytes`);
  console.log(`Text Blob content: ${await textBlob.text()}`);

  // Create a File from an existing file path, without reading into memory
  const fsFile = fileFromSync(testFilePath, 'text/plain');
  console.log(`FS File name: ${fsFile.name}`);
  console.log(`FS File size: ${fsFile.size} bytes`);
  console.log(`FS File last modified: ${new Date(fsFile.lastModified).toISOString()}`);

  // Combine multiple Blob/File parts into a new Blob
  const combinedBlob = new Blob([textBlob, fsFile, new Uint8Array([1, 2, 3])]);
  console.log(`Combined Blob size: ${combinedBlob.size} bytes`);

  // Read the combined blob's stream as a Node.js Readable
  const nodeStream = Readable.from(combinedBlob.stream());
  let streamContent = '';
  for await (const chunk of nodeStream) {
    streamContent += chunk.toString();
  }
  console.log(`Combined Blob stream content (partial): ${streamContent.substring(0, 50)}...`);

  // Clean up the temporary file
  if (existsSync(testFilePath)) {
    unlinkSync(testFilePath);
  }
}

runQuickstart().catch(console.error);

view raw JSON →