File tree Expand file tree Collapse file tree 3 files changed +34
-12
lines changed
node-http-handler/src/stream-collector Expand file tree Collapse file tree 3 files changed +34
-12
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ " @smithy/fetch-http-handler " : patch
3
+ " @smithy/node-http-handler " : patch
4
+ ---
5
+
6
+ improve stream collection speed
Original file line number Diff line number Diff line change @@ -17,20 +17,28 @@ async function collectBlob(blob: Blob): Promise<Uint8Array> {
17
17
}
18
18
19
19
async function collectStream ( stream : ReadableStream ) : Promise < Uint8Array > {
20
- let res = new Uint8Array ( 0 ) ;
20
+ const chunks = [ ] ;
21
21
const reader = stream . getReader ( ) ;
22
22
let isDone = false ;
23
+ let length = 0 ;
24
+
23
25
while ( ! isDone ) {
24
26
const { done, value } = await reader . read ( ) ;
25
27
if ( value ) {
26
- const prior = res ;
27
- res = new Uint8Array ( prior . length + value . length ) ;
28
- res . set ( prior ) ;
29
- res . set ( value , prior . length ) ;
28
+ chunks . push ( value ) ;
29
+ length += value . length ;
30
30
}
31
31
isDone = done ;
32
32
}
33
- return res ;
33
+
34
+ const collected = new Uint8Array ( length ) ;
35
+ let offset = 0 ;
36
+ for ( const chunk of chunks ) {
37
+ collected . set ( chunk , offset ) ;
38
+ offset += chunk . length ;
39
+ }
40
+
41
+ return collected ;
34
42
}
35
43
36
44
function readToBase64 ( blob : Blob ) : Promise < string > {
Original file line number Diff line number Diff line change @@ -35,18 +35,26 @@ const isReadableStreamInstance = (stream: unknown): stream is IReadableStream =>
35
35
typeof ReadableStream === "function" && stream instanceof ReadableStream ;
36
36
37
37
async function collectReadableStream ( stream : IReadableStream ) : Promise < Uint8Array > {
38
- let res = new Uint8Array ( 0 ) ;
38
+ const chunks = [ ] ;
39
39
const reader = stream . getReader ( ) ;
40
40
let isDone = false ;
41
+ let length = 0 ;
42
+
41
43
while ( ! isDone ) {
42
44
const { done, value } = await reader . read ( ) ;
43
45
if ( value ) {
44
- const prior = res ;
45
- res = new Uint8Array ( prior . length + value . length ) ;
46
- res . set ( prior ) ;
47
- res . set ( value , prior . length ) ;
46
+ chunks . push ( value ) ;
47
+ length += value . length ;
48
48
}
49
49
isDone = done ;
50
50
}
51
- return res ;
51
+
52
+ const collected = new Uint8Array ( length ) ;
53
+ let offset = 0 ;
54
+ for ( const chunk of chunks ) {
55
+ collected . set ( chunk , offset ) ;
56
+ offset += chunk . length ;
57
+ }
58
+
59
+ return collected ;
52
60
}
You can’t perform that action at this time.
0 commit comments