Busboy Streaming Multipart Limits

Parse multipart request bodies with Busboy in streaming mode, enforcing file count, size, and type limits before any bytes hit disk.

TypescriptNodeFile Upload

Code

typescriptsnippet
47 lines
import busboy from 'busboy';
import { createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
import type { IncomingMessage } from 'node:http';

const LIMITS = {
  fileSize: 10 * 1024 * 1024,
  files: 2,
  fields: 12,
};

const ALLOWED_TYPES = /^(image\/png|image\/webp|application\/pdf)$/;

export function handleUpload(req: IncomingMessage): Promise<{
  files: { name: string; bytes: number }[];
  fields: Record<string, string>;
}> {
  return new Promise((resolve, reject) => {
    const parser = busboy({
      headers: req.headers,
      limits: LIMITS,
    });

    const files: { name: string; bytes: number }[] = [];
    const fields: Record<string, string> = {};

    parser.on('file', (name, stream, info) => {
      if (!ALLOWED_TYPES.test(info.mimeType)) {
        stream.resume(); // 必须消费掉流,否则解析停滞
        reject(new Error('unsupported type: ' + info.mimeType));
        return;
      }
      const target = createWriteStream('uploads/' + info.filename);
      pipeline(stream, target).catch(reject);
      files.push({ name: info.filename, bytes: stream.readableLength });
    });

    parser.on('field', (name, value) => {
      fields[name] = value.slice(0, 500);
    });

    parser.on('close', () => resolve({ files, fields }));
    parser.on('error', reject);

    req.pipe(parser);
  });
}

How it works

Busboy Streaming Multipart Limits keeps everything in the function handleUpload.

createWriteStream, pipeline are the only symbols borrowed from busboy — the coupling is explicit and narrow.

What comes back is a new object, not a reference to anything passed in.

What to watch for

  • External dependency: busboy — install it before running the snippet.

Applying it

The primary signature is export function handleUpload(req: IncomingMessage)

Import handleUpload from the file and call it — the rest of the code is implementation detail.

Statements that matter

parser.on('close', () => resolve({ files, fields }));
pipeline(stream, target).catch(reject);
parser.on('field', (name, value) => {
fields[name] = value.slice(0, 500);
});

FAQ

Does `handleUpload` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
Which packages must be installed first?
Yes. The imports resolve to `busboy`, which the package manager must provide.