fetch-multipart-parser
is a streaming multipart parser for JavaScript's fetch API.
This package is a streaming multipart parser for JavaScript's fetch API, making it easy to parse incoming Request
bodies that are generated by <form enctype="multipart/form-data">
in the browser.
$ npm install fetch-multipart-parser
import { MultipartParseError, parseMultipartFormData } from 'fetch-multipart-parser';
function handleMultipartRequest(request: Request): void {
try {
// The parser `yield`s each part as a MultipartPart as it becomes available.
for await (let part of parseMultipartFormData(request)) {
console.log(part.name);
console.log(part.filename);
console.log(part.mediaType);
if (/^text\//.test(part.mediaType)) {
console.log(new TextDecoder().decode(part.content));
} else {
// part.content is binary data, save it to a file
}
}
} catch (error) {
if (error instanceof MultipartParseError) {
console.error('Failed to parse multipart/form-data:', error.message);
} else {
console.error('An unexpected error occurred:', error);
}
}
}
The results of running the benchmarks on my laptop:
Platform: Darwin (23.5.0)
CPU: Apple M2 Pro
Node.js v20.15.1
Date: 7/26/2024, 4:04:11 PM
┌────────────────────────┬──────────────────┬──────────────────┬──────────────────┬───────────────────┐
│ (index) │ 1 small file │ 1 large file │ 100 small files │ 5 large files │
├────────────────────────┼──────────────────┼──────────────────┼──────────────────┼───────────────────┤
│ fetch-multipart-parser │ '0.02 ms ± 0.13' │ '2.03 ms ± 0.75' │ '0.34 ms ± 0.15' │ '21.86 ms ± 2.24' │
│ busboy │ '0.03 ms ± 0.09' │ '4.11 ms ± 0.20' │ '0.23 ms ± 0.03' │ '45.13 ms ± 3.22' │
│ @fastify/busboy │ '0.03 ms ± 0.08' │ '2.05 ms ± 0.20' │ '0.38 ms ± 0.04' │ '27.88 ms ± 2.84' │
└────────────────────────┴──────────────────┴──────────────────┴──────────────────┴───────────────────┘