TypeScript streaming parser for MIME multipart messages
npm install @apeleghq/multipart-parsernpm or yarn:
sh
npm install @apeleghq/multipart-parser
`
`sh
yarn add @apeleghq/multipart-parser
`
🎬 Usage
The library exports the function parseMultipartMessage, which returns an async
generator that yields objects with the headers and body (as a Uint8Array) of
each part in the multipart message.
$3
#### parseMultipartMessage(stream: ReadableStream, boundary: string): AsyncGenerator
This function takes a ReadableStream and a boundary string as arguments, and
returns an asynchronous generator that yields objects with the following
properties:
* headers: a Headers object containing the headers of the current part
* body: a Uint8Array containing the body of the current part, or null if
the part is empty.
* parts: a nested iterator of the same structure for any parts within the
current part, if the part's Content-Type header indicates that it is a
multipart message.
#### boundaryRegex: RegExp
A regular expression that can be used to validate a boundary string.
#### boundaryMatchRegex: RegExp
A regular expression that can be used to extract a boundary string from a
Content-Type header.
#### encodeMultipartMessage(boundary: string, msg: AsyncIterable
This function takes a boundary string and an array of messages as arguments and returns a ReadableStream that can be read to obtain a multipart message.
TDecodedMultipartMessage is defined as an object with the following fields:
* headers: a Headers object containing the headers of the current part
* body (optional): The body of the current part, or null if the part is
empty. It can be any of the following types: ArrayBuffer, Blob, ReadableStream or any typed array, such as Uint8Array.
* parts (optional): An async or sync iterable of one element or more of
the same type (TDecodedMultipartMessage), for nested messages. If both
body and parts are specified, body takes precedence.
$3
`js
import { parseMultipartMessage } from '@apeleghq/multipart-message-parser';
const decoder = new TextDecoder();
const stream = ... // a ReadableStream containing the multipart message
const boundary = 'my-boundary'; // the boundary of the multipart message
for await (const part of parseMultipartMessage(stream, boundary)) {
console.log(part.headers.get('content-type'));
console.log(decoder.decode(part.body));
}
``