Multipart Streaming With Busboy

Parse multipart uploads with busboy streaming for memory-efficient large file handling with limits.

TypescriptFile Upload

Code

typescriptsnippet
1 line
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);});}

Inside the snippet

Multipart Streaming With Busboy keeps everything in the function parseMultipart.

Reach for busboy and what you get is Writable — that is the whole API contact area.

The result is a fresh construction, so callers can keep their originals.

Points of care

  • Plan for an install step: busboy is a real dependency, resolved by the package manager.

Using it

The primary signature is export function parseMultipart(req:{headers:Record<string,string>},{maxFileSize=10*1024*1024}={})

Import parseMultipart from the file and call it — the rest of the code is implementation detail.

FAQ

Does `parseMultipart` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
Do I need to install anything before running this?
Yes: `busboy` must be present in the project or the import fails at load time.