Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support Blob.stream(). #1500

Merged
merged 2 commits into from
Aug 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions packages/happy-dom/src/file/Blob.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Buffer } from 'buffer';
import { ReadableStream } from 'stream/web';
import * as PropertySymbol from '../PropertySymbol.js';

/**
Expand Down Expand Up @@ -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.
*
Expand Down
18 changes: 18 additions & 0 deletions packages/happy-dom/test/file/Blob.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
Expand Down
Loading