0.0.1 • Published 6 months ago

@matrix-js/multipart-mixed v0.0.1

Weekly downloads
-
License
GPL-3.0
Repository
-
Last release
6 months ago

@matrixjs/multipart-mixed

Promise-based multipart/mixed parser, with support for Streams. Originally developed and tested for federated Matrix media downloads [spec], though should be flexible enough for other parsing.

API

multipartMixed(httpStream, expectedParts[])

  • httpStream: HTTP response stream (http.IncomingMessage).
  • expectedParts: Array of expected parts, in the expected order. Can be:
    • {responseType: "buffer"} (default), returns this part as a raw Buffer.
    • {responseType: "string"}, returns as string (UTF-8).
    • {responseType: "json"}, parses part as JSON.
    • {responseType: "stream"}, returns a stream for the part's content as soon as it starts. needs to be read completely to continue parsing succeeding parts, supports backpressure.

Returns a Promise, which resolves into an array of promises, one for each expected part, as soon as the initial HTTP headers are correct, and multiparts are being processed. As each part is sequentially encountered in the HTTP stream, these promises resolve with an object. buffer/string/json parts resolve as {headers: {}, body: string|Buffer|{}}. Streams as {headers: {}, stream: Stream}. Headers are parsed HTTP headers for that individual part, with header names all lowercase (using http-headers).

Example

// FIXME: example.com doesn't actually give a multipart/mixed response.
// Repo has 
axios.get("https://example.com", { responseType: "stream" })
	.then((res) => {
		return multipartMixed(
			res.data,
			[
				{ name: "meta", responseType: "json" },
				{ name: "media", responseType: "stream" },
			],
		);
	}).then(([jsonPromise, mediaPromise]) => {
		jsonPromise.then((json) => {
			console.log("json:", json); // {headers: {...}, body: {json: "yes"}}
		});

		mediaPromise.then((media) => {
			console.log("media:", media); // {headers: {...}, stream: Part {...}}
		});
	});

License, donations

GPL-3.0. If you want to support my work, you can:

Changelog

0.0.1 (April 19th, 2025)

  • Initial release