From fec1c0165753112715e1295cc57bb0c16b679b39 Mon Sep 17 00:00:00 2001 From: PlopAndRun Date: Fri, 30 Aug 2024 00:55:57 +0300 Subject: [PATCH] feat: [#1500] Adds support for Blob.stream() (#1500) Co-authored-by: David Ortner --- packages/happy-dom/src/file/Blob.ts | 16 ++++++++++++++++ packages/happy-dom/test/file/Blob.test.ts | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/packages/happy-dom/src/file/Blob.ts b/packages/happy-dom/src/file/Blob.ts index c694d8f65..edf6fbc2a 100644 --- a/packages/happy-dom/src/file/Blob.ts +++ b/packages/happy-dom/src/file/Blob.ts @@ -1,4 +1,5 @@ import { Buffer } from 'buffer'; +import { ReadableStream } from 'stream/web'; import * as PropertySymbol from '../PropertySymbol.js'; /** @@ -136,6 +137,21 @@ export default class Blob { return this[PropertySymbol.buffer].toString(); } + /** + * Returns returns a ReadableStream which upon reading returns the data contained within the Blob. + * + * @returns ReadableStream + */ + public stream(): ReadableStream { + const buffer = this[PropertySymbol.buffer]; + return new ReadableStream({ + start(controller) { + controller.enqueue(buffer); + controller.close(); + } + }); + } + /** * Returns the object converted to string. * diff --git a/packages/happy-dom/test/file/Blob.test.ts b/packages/happy-dom/test/file/Blob.test.ts index 6bb0cd578..bfc37f2d1 100644 --- a/packages/happy-dom/test/file/Blob.test.ts +++ b/packages/happy-dom/test/file/Blob.test.ts @@ -38,6 +38,24 @@ describe('Blob', () => { }); }); + describe('stream()', () => { + it('Returns all data in a ReadableStream.', async () => { + const data = 'Test1Test2'; + const blob = new Blob(['Test1', 'Test2']); + const stream = blob.stream(); + + let i = 0; + for await (const chunk of stream.values()) { + for (const value of chunk) { + expect(i).toBeLessThan(data.length); + expect(value).toBe(data[i].charCodeAt(0)); + ++i; + } + } + expect(i).toBe(data.length); + }); + }); + describe('toString()', () => { it('Returns "[object Blob]".', () => { const blob = new Blob(['TEST']);