-
Notifications
You must be signed in to change notification settings - Fork 50
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add stream support and fix some bugs (#28)
* feat: add stream support and fix some bugs * fix: typo length --------- Co-authored-by: 唐烨 <[email protected]>
- Loading branch information
1 parent
e61a34a
commit b0c4161
Showing
4 changed files
with
143 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,27 @@ | ||
import type { Writable } from 'node:stream' | ||
|
||
export async function writeReadableStreamToWritable(stream: ReadableStream, writable: Writable) { | ||
let reader = stream.getReader() | ||
const reader = stream.getReader() | ||
|
||
async function read() { | ||
let { done, value } = await reader.read() | ||
function onClose() { | ||
reader.cancel(new Error('Response writer closed')) | ||
} | ||
|
||
if (done) { | ||
writable.end() | ||
return | ||
} | ||
writable.once('close', onClose) | ||
|
||
writable.write(value) | ||
try { | ||
while (true) { | ||
const { done, value } = await reader.read() | ||
|
||
await read() | ||
} | ||
if (done) { | ||
writable.end() | ||
return | ||
} | ||
|
||
try { | ||
await read() | ||
} catch (error: any) { | ||
writable.destroy(error) | ||
throw error | ||
writable.write(value) | ||
} | ||
} finally { | ||
writable.off('close', onClose) | ||
reader.releaseLock() | ||
} | ||
} | ||
|
||
/** | ||
* Credits: | ||
* - https://github.com/remix-run/remix/blob/e77e2eb/packages/remix-node/stream.ts | ||
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters