File Upload Stream With Size Limit
Stream uploaded files to disk with size limit magic byte validation and temp directory cleanup for safe multipart handling.
Code
import fs from'node:fs';import path from'node:path';import crypto from'node:crypto';const MAGIC={png:Buffer.from([0x89,0x50,0x4e,0x47]),jpg:Buffer.from([0xff,0xd8,0xff]),gif:Buffer.from([0x47,0x49,0x46])};export async function streamUpload(stream,{maxSize=10*1024*1024,allowedTypes=['png','jpg','gif'],destDir='/tmp'}={}){const tmp=path.join(destDir,crypto.randomUUID());let size=0,header=Buffer.alloc(0);const ws=fs.createWriteStream(tmp);for await(const chunk of stream){size+=chunk.length;if(size>maxSize){ws.destroy();fs.unlinkSync(tmp);throw new Error('file too large');}if(header.length<4)header=Buffer.concat([header,chunk]);for(const[type,magic]of Object.entries(MAGIC))if(allowedTypes.includes(type)&&header.subarray(0,magic.length).equals(magic))break;ws.write(chunk);}ws.end();await new Promise(r=>ws.on('finish',r));return{path:tmp,size};}Report a problem with this exampleOpens a pre-filled issue on GitHub.