Multipart Streaming With Busboy
Parse multipart uploads with busboy streaming for memory-efficient large file handling with limits.
Code
import Busboy from'busboy';import{Writable}from'node:stream';export function parseMultipart(req:{headers:Record<string,string>},{maxFileSize=10*1024*1024}={}){const busboy=Busboy({headers:req.headers,limits:{fileSize:maxFileSize}});const files:{fieldname:string;filename:string;data:Buffer;}[]=[];const fields:Record<string,string>={};busboy.on('file',(fieldname,file,filename)=>{const chunks:Buffer[]=[];file.on('data',(c)=>chunks.push(c));file.on('end',()=>files.push({fieldname,filename:filename??'',data:Buffer.concat(chunks)}));});busboy.on('field',(name,val)=>{fields[name]=val;});return new Promise<{files:typeof files;fields:typeof fields}>((resolve,reject)=>{busboy.on('finish',()=>resolve({files,fields}));busboy.on('error',reject);req.pipe?.(busboy);});}Report a problem with this exampleOpens a pre-filled issue on GitHub.