@@ -4,38 +4,31 @@ export async function fromReadableStream(
4
4
stream : ReadableStream < Uint8Array > ,
5
5
base64 ?: boolean ,
6
6
) : Promise < string > {
7
- const reader = stream . getReader ( ) ;
8
7
const chunks : Uint8Array [ ] = [ ] ;
9
8
let totalLength = 0 ;
10
9
11
- try {
12
- while ( true ) {
13
- const { done, value } = await reader . read ( ) ;
14
- if ( done ) break ;
15
- chunks . push ( value ) ;
16
- totalLength += value . length ;
17
- }
18
-
19
- if ( chunks . length === 0 ) {
20
- return "" ;
21
- }
10
+ for await ( const chunk of stream ) {
11
+ chunks . push ( chunk ) ;
12
+ totalLength += chunk . length ;
13
+ }
22
14
23
- if ( chunks . length === 1 ) {
24
- return Buffer . from ( chunks [ 0 ] ) . toString ( base64 ? "base64" : "utf8" ) ;
25
- }
15
+ if ( chunks . length === 0 ) {
16
+ return "" ;
17
+ }
26
18
27
- // Pre-allocate buffer with exact size to avoid reallocation
28
- const buffer = Buffer . allocUnsafe ( totalLength ) ;
29
- let offset = 0 ;
30
- for ( const chunk of chunks ) {
31
- buffer . set ( chunk , offset ) ;
32
- offset += chunk . length ;
33
- }
19
+ if ( chunks . length === 1 ) {
20
+ return Buffer . from ( chunks [ 0 ] ) . toString ( base64 ? "base64" : "utf8" ) ;
21
+ }
34
22
35
- return buffer . toString ( base64 ? "base64" : "utf8" ) ;
36
- } finally {
37
- reader . releaseLock ( ) ;
23
+ // Pre-allocate buffer with exact size to avoid reallocation
24
+ const buffer = Buffer . alloc ( totalLength ) ;
25
+ let offset = 0 ;
26
+ for ( const chunk of chunks ) {
27
+ buffer . set ( chunk , offset ) ;
28
+ offset += chunk . length ;
38
29
}
30
+
31
+ return buffer . toString ( base64 ? "base64" : "utf8" ) ;
39
32
}
40
33
41
34
export function toReadableStream (
0 commit comments