@@ -17,28 +17,34 @@ const resolvePost = req =>
1717 } ) ;
1818 } ) ;
1919
20- const pipStream = ( path , writeStream ) =>
21- new Promise ( resolve => {
22- const readStream = fse . createReadStream ( path ) ;
23- writeStream . on ( 'finish' , ( ) => {
24- writeStream . end ( ) ;
25- fse . unlinkSync ( path ) ;
20+ const pipeStream = ( path , writeStream , chunkSize ) =>
21+ new Promise ( ( resolve , reject ) => {
22+ const readStream = fse . createReadStream ( path , {
23+ highWaterMark : chunkSize
24+ } ) ;
25+ readStream . on ( 'end' , ( ) => {
26+ // fse.unlinkSync(path);
27+ readStream . unpipe ( ) ;
2628 resolve ( ) ;
2729 } ) ;
28- readStream . pipe ( writeStream ) ;
30+ readStream . pipe ( writeStream , { end : false } ) ;
31+ readStream . on ( 'error' , reject ) ;
2932 } ) ;
3033
31- const mergeFileChunk = async ( fileHash , fileName , size ) => {
34+ const mergeFileChunk = async ( fileHash , fileName , chunkSize ) => {
3235 const filePath = path . resolve ( UPLOAD_DIR , `${ fileHash } ${ extractExt ( fileName ) } ` ) ;
3336 const chunkDir = path . resolve ( UPLOAD_DIR , fileHash ) ;
3437 const chunkPaths = await fse . readdir ( chunkDir ) ;
3538 chunkPaths . sort ( ( a , b ) => a . slice ( a . lastIndexOf ( '-' ) + 1 ) - b . slice ( b . lastIndexOf ( '-' ) + 1 ) ) ;
36- await Promise . all ( chunkPaths . map ( ( chunkPath , index ) =>
37- pipStream ( path . resolve ( chunkDir , chunkPath ) , fse . createWriteStream ( filePath , {
38- start : index * size
39- } ) )
40- ) ) ;
41- fse . rmdirSync ( chunkDir ) ; // 合并完成后删除切片目录
39+ const writeStream = fse . createWriteStream ( filePath ) ;
40+ await Promise . all ( chunkPaths . map ( ( chunkPath , index ) =>
41+ pipeStream ( path . resolve ( chunkDir , chunkPath ) , writeStream , chunkSize )
42+ ) ) . then ( ( ) => {
43+ // close the stream to prevent memory leaks
44+ writeStream . close ( ) ;
45+ return Promise . resolve ( filePath ) ;
46+ } )
47+ // fse.rmdirSync(chunkDir); // 合并完成后删除切片目录
4248} ;
4349
4450module . exports = {
@@ -47,8 +53,8 @@ module.exports = {
4753 } ,
4854 async handleMerge ( req , res ) {
4955 const data = await resolvePost ( req ) ;
50- const { fileHash, fileName, size } = data ;
51- await mergeFileChunk ( fileHash , fileName , size ) ;
56+ const { fileHash, fileName, chunkSize } = data ;
57+ await mergeFileChunk ( fileHash , fileName , chunkSize ) ;
5258 res . end ( JSON . stringify ( {
5359 code : 0 ,
5460 msg : 'file merged success'
0 commit comments