@@ -40,7 +40,8 @@ Section -> Buffer
4040
4141// "wpc" + 1 in little-endian
4242const VERSION = 0x01637077 ;
43- const _1GiB = 1 * 1024 * 1024 * 1024 ;
43+ const WRITE_LIMIT_TOTAL = 0x7fff0000 ;
44+ const WRITE_LIMIT_CHUNK = 511 * 1024 * 1024 ;
4445
4546/**
4647 * @param {Buffer[] } buffers buffers
@@ -454,22 +455,42 @@ class FileMiddleware extends SerializerMiddleware {
454455 stream . on ( "error" , err => reject ( err ) ) ;
455456 stream . on ( "finish" , ( ) => resolve ( ) ) ;
456457 }
457- // use unsafe
458- if ( size <= _1GiB ) {
459- for ( const b of content ) stream . write ( b ) ;
460- return stream . end ( ) ;
458+ // split into chunks for WRITE_LIMIT_CHUNK size
459+ const chunks = [ ] ;
460+ for ( const b of content ) {
461+ if ( b . length < WRITE_LIMIT_CHUNK ) {
462+ chunks . push ( b ) ;
463+ } else {
464+ for ( let i = 0 ; i < b . length ; i += WRITE_LIMIT_CHUNK ) {
465+ chunks . push ( b . slice ( i , i + WRITE_LIMIT_CHUNK ) ) ;
466+ }
467+ }
461468 }
462469
463- const len = content . length ;
470+ const len = chunks . length ;
464471 let i = 0 ;
465472 const batchWrite = err => {
473+ // will be handled in "on" error handler
474+ if ( err ) return ;
475+
466476 if ( i === len ) {
467477 stream . end ( ) ;
468478 return ;
469479 }
470- // will be handle in "on" handler
471- if ( err ) return ;
472- stream . write ( content [ i ++ ] , batchWrite ) ;
480+
481+ // queue up a batch of chunks up to the write limit
482+ // end is exclusive
483+ let end = i ;
484+ let sum = chunks [ end ++ ] . length ;
485+ while ( end < len ) {
486+ sum += chunks [ end ] . length ;
487+ if ( sum > WRITE_LIMIT_TOTAL ) break ;
488+ end ++ ;
489+ }
490+ while ( i < end - 1 ) {
491+ stream . write ( chunks [ i ++ ] ) ;
492+ }
493+ stream . write ( chunks [ i ++ ] , batchWrite ) ;
473494 } ;
474495 batchWrite ( ) ;
475496 } ) ;
0 commit comments