Get started with Meros in minutes by learning how to read multipart responses in both browser and Node.js environments
This guide will help you get up and running with Meros quickly. You’ll learn how to handle multipart responses in both browser and Node.js environments with real working examples.
The multiple option is an optimization technique that yields all available parts of a chunk at once, rather than yielding once per part. This is particularly useful for technologies like GraphQL where you can process multiple parts synchronously.
const chunks = await fetch('/api').then((response) => meros(response, { multiple: true }));for await (const parts of chunks) { // parts is now an array for (const part of parts) { console.log(part.body); }}
Setting multiple: true changes the behavior to yield arrays instead of individual parts. Make sure to adjust your code accordingly.
import { meros } from 'meros';import { from } from 'rxjs';const parts = await fetch('/api').then(meros);from(parts).subscribe((part) => { if (part.json) { console.log('JSON data:', part.body); } else { console.log('Raw data:', part.body); }});
Meros will return the original response if the content type is not multipart. This makes it safe to use as middleware:
import { meros } from 'meros';const response = await fetch('/api');const parts = await meros(response);if (parts[Symbol.asyncIterator]) { // It's multipart - iterate over parts for await (const part of parts) { console.log(part.body); }} else { // It's a regular response - handle normally const data = await parts.json(); console.log(data);}
Meros returns the original response unchanged when the content type is not multipart/mixed, making it perfect for middleware chains.
Handle errors gracefully when working with multipart streams:
import { meros } from 'meros';try { const parts = await fetch('/api').then(meros); for await (const part of parts) { try { if (part.json) { // Process JSON part console.log(part.body); } else { // Process raw part console.log(part.body.toString()); } } catch (partError) { console.error('Error processing part:', partError); // Continue processing other parts } }} catch (error) { console.error('Error fetching or parsing multipart response:', error);}
Meros provides full TypeScript support with generic types:
import { meros } from 'meros';import type { Part } from 'meros';interface User { id: string; name: string; email: string;}const parts = await fetch('/users').then((r) => meros<User>(r));for await (const part of parts) { if (part.json) { // part.body is typed as User console.log(part.body.name); }}