it-multipart: Async Iterable Multipart Parser

3.0.14 · active · verified Wed Apr 22

it-multipart is a JavaScript library designed to parse HTTP multipart messages using async iterables. It provides a robust and modern approach to handling streaming data from HTTP requests, particularly useful for file uploads or complex form data. Currently at version 3.0.14, it is part of the broader `it` (InterPlanetary Stream) ecosystem, which emphasizes composable, stream-based utilities. The project demonstrates active maintenance, with frequent updates to various `it-*` packages within its monorepo, suggesting a stable and evolving codebase. Its key differentiator lies in its deep integration with JavaScript's async iterable protocol, making it highly efficient for non-blocking I/O operations and suitable for both Node.js server environments and potentially browser-side stream processing where async iterables are supported. It ships with TypeScript types, ensuring a better developer experience for TypeScript users.

Common errors

Warnings

Install

Imports

Quickstart

This code demonstrates how to create an HTTP server that listens for POST requests with a 'multipart/form-data' content type, parses the incoming multipart message using `it-multipart`, and logs the headers and content of each part.

import http from 'http'
import multipart from 'it-multipart'

const server = http.createServer(async (req, res) => {
  if (req.method === 'POST' && req.headers['content-type']) {
    try {
      const boundary = req.headers['content-type'].split('boundary=')[1]
      if (!boundary) {
        res.writeHead(400, { 'Content-Type': 'text/plain' })
        res.end('Missing boundary in Content-Type header')
        return
      }

      for await (const part of multipart(req, boundary)) {
        console.log(`Received part with headers:`, part.headers)

        let partContent = ''
        // nb. part.body must be consumed before the next part is emitted
        for await (const chunk of part.body) {
          partContent += chunk.toString()
        }
        console.log(`Part name: ${part.name}, Content:`, partContent)
      }

      console.log('Finished parsing multipart message.')
      res.writeHead(200, { 'Content-Type': 'text/plain' })
      res.end('Multipart message parsed successfully.')
    } catch (error) {
      console.error('Error parsing multipart message:', error)
      res.writeHead(500, { 'Content-Type': 'text/plain' })
      res.end('Error parsing multipart message: ' + error.message)
    }
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' })
    res.end('Not Found or Unsupported Method')
  }
})

server.listen(5001, () => {
  console.log('Server listening on port 5001')
})

// Example usage with curl:
// curl -X POST -H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "field1=value1" -F "file1=@./package.json" http://localhost:5001

view raw JSON →