Skip to content

Commit

Permalink
Merge pull request #2 from Borewit/fix-end-of-stream-handling
Browse files Browse the repository at this point in the history
Fix stream is hanging reading the remainder of the stream
  • Loading branch information
Borewit authored Feb 2, 2025
2 parents 837a5cf + 4538569 commit 6a4b8af
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 8 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ const webReadable = makeByteReadableStreamFromNodeReadable(nodeReadable);
// Now you can use webReadable as a WHATWG ReadableStream
```

## Compatibility

This is an ECMAScript Module (ESM).


## API

### `toWebReadableStream(nodeReadable)`
Expand Down
9 changes: 1 addition & 8 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,7 @@ export function makeByteReadableStreamFromNodeReadable(nodeReadable: Readable):
nodeReadable.resume();
},
pull(controller: ReadableByteStreamController) {
if (leftoverChunk) {
processLeftover(controller);
return;
}
if (isNodeStreamEnded) {
controller.close();
return;
}
processLeftover(controller);
},
cancel(reason) {
nodeReadable.destroy(reason);
Expand Down
28 changes: 28 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,34 @@ describe('makeByteReadableStreamFromFile()', () => {
}
});

it('read more data then available #2', async () => {
const nodeReadable = new SourceStream('123');
try {
const webReadableStream = makeByteReadableStreamFromNodeReadable(nodeReadable);
try {
const streamReader = webReadableStream.getReader({mode: 'byob'});
try {

let res;
let buf = new Uint8Array(4);
res = await streamReader.read(buf);
assert.strictEqual(res.done, false, 'result.done');
assert.equal(res.value.length, 3, 'should indicate only 3 bytes are actually read');
buf = new Uint8Array(4);
res = await streamReader.read(buf);
assert.strictEqual(res.done, true, 'result.done');
assert.equal(res.value.length, 0, 'should indicate no more bytes are available');
} finally {
streamReader.releaseLock();
}
} finally {
await webReadableStream.cancel();
}
} finally {
nodeReadable.destroy();
}
});

it('read from a streamed data chunk', async () => {
const nodeReadable = new SourceStream('\x05peter');
try {
Expand Down

0 comments on commit 6a4b8af

Please sign in to comment.