@@ -107,6 +107,28 @@ export default class RemoteFile implements GenericFilehandle {
107107 }
108108 }
109109
110+ const { downloadCallback } = opts
111+ if ( downloadCallback && res . body ) {
112+ const total = parseInt ( res . headers . get ( 'content-length' ) ?? '0' , 10 )
113+ const reader = res . body . getReader ( )
114+ const chunks : Uint8Array [ ] = [ ]
115+ let downloaded = 0
116+ let result = await reader . read ( )
117+ while ( ! result . done ) {
118+ chunks . push ( result . value )
119+ downloaded += result . value . byteLength
120+ downloadCallback ( downloaded , total )
121+ result = await reader . read ( )
122+ }
123+ const resData = new Uint8Array ( downloaded )
124+ let offset = 0
125+ for ( const chunk of chunks ) {
126+ resData . set ( chunk , offset )
127+ offset += chunk . byteLength
128+ }
129+ return resData . byteLength <= length ? resData : resData . subarray ( 0 , length )
130+ }
131+
110132 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
111133 const resData = res . bytes
112134 ? await res . bytes ( )
@@ -161,6 +183,27 @@ export default class RemoteFile implements GenericFilehandle {
161183 } else if ( encoding ) {
162184 throw new Error ( `unsupported encoding: ${ encoding } ` )
163185 } else {
186+ const { downloadCallback } = opts
187+ if ( downloadCallback && res . body ) {
188+ const total = parseInt ( res . headers . get ( 'content-length' ) ?? '0' , 10 )
189+ const reader = res . body . getReader ( )
190+ const chunks : Uint8Array [ ] = [ ]
191+ let downloaded = 0
192+ let result = await reader . read ( )
193+ while ( ! result . done ) {
194+ chunks . push ( result . value )
195+ downloaded += result . value . byteLength
196+ downloadCallback ( downloaded , total )
197+ result = await reader . read ( )
198+ }
199+ const resData = new Uint8Array ( downloaded )
200+ let offset = 0
201+ for ( const chunk of chunks ) {
202+ resData . set ( chunk , offset )
203+ offset += chunk . byteLength
204+ }
205+ return resData
206+ }
164207 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
165208 return res . bytes ? res . bytes ( ) : new Uint8Array ( await res . arrayBuffer ( ) )
166209 }
0 commit comments