@ts-stack/multiparty

multipart/form-data parser which supports streaming, writen in TypeScript

Usage no npm install needed!

<script type="module">
  import tsStackMultiparty from 'https://cdn.skypack.dev/@ts-stack/multiparty';
</script>

README

@ts-stack/multiparty

Parse http requests with content-type multipart/form-data, also known as file uploads.

This is fork of multiparty from this state, writen in TypeScript.

Installation

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

npm install @ts-stack/multiparty

Usage

Parse an incoming multipart/form-data request.

import http = require('http');
import util = require('util');
import { Form } from '@ts-stack/multiparty';

http.createServer((req, res) => {
  if (req.url == '/upload' && req.method == 'POST') {
    // parse a file upload
    const form = new Form();

    form.parse(req, (err, fields, files) => {
      res.writeHead(200, { 'content-type': 'text/plain' });
      res.write('received upload:\n\n');
      res.end(util.inspect({ fields: fields, files: files }));
    });

    return;
  }

  // show a file upload form
  res.writeHead(200, { 'content-type': 'text/html' });
  res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title"><br>'+
    '<input type="file" name="upload" multiple="multiple"><br>'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );
}).listen(8080);

API

Form

import { Form } from '@ts-stack/multiparty';

const form = new Form(options)

Creates a new form.

export class FormOptions {
  /**
   * Sets encoding for the incoming form fields. Defaults to `utf8`.
   */
  encoding?: BufferEncoding;
  /**
   * Limits the amount of memory all fields (not files) can allocate in bytes.
   * If this value is exceeded, an `error` event is emitted.
   * The default size is 2MB.
   */
  maxFieldsSize?: number;
  /**
   * Limits the number of fields that will be parsed before emitting an `error` event.
   * A file counts as a field in this case. Defaults to 1000.
   */
  maxFields?: number;
  /**
   * Only relevant when `autoFiles` is `true`.
   * Limits the total bytes accepted for all files combined.
   * If this value is exceeded, an `error` event is emitted.
   * The default is `Infinity`.
   */
  maxFilesSize?: number;
  /**
   * Enables `field` events and disables `part` events for fields.
   * This is automatically set to `true` if you add a `field` listener.
   */
  autoFields?: boolean;
  /**
   * Enables `file` events and disables `part` events for files.
   * This is automatically set to `true` if you add a `file` listener.
   */
  autoFiles?: boolean;
  /**
   * Only relevant when `autoFiles` is `true`.
   * The directory for placing file uploads in.
   * You can move them later using `fs.rename()`.
   * Defaults to `os.tmpdir()`.
   */
  uploadDir?: string;
}

form.parse(request, cb?)

Parses an incoming node.js request containing form data.This will cause form to emit events based off the incoming request.

import { Form } from '@ts-stack/multiparty';

// ...

let count = 0;
const form = new Form();

// Errors may be emitted
// Note that if you are listening to 'part' events, the same error may be
// emitted from the `form` and the `part`.
form.on('error', (err) => {
  console.log('Error parsing form: ' + err.stack);
});

// Parts are emitted when parsing the form
form.on('part', (part) => {
  // You *must* act on the part by reading it
  // NOTE: if you want to ignore it, just call "part.resume()"

  if (!part.filename) {
    // filename is not defined when this is a field and not a file
    console.log('got field named ' + part.name);
    // ignore field's content
    part.resume();
  }

  if (part.filename) {
    // filename is defined when this is a file
    count++;
    console.log('got file named ' + part.name);
    // ignore file's content here
    part.resume();
  }

  part.on('error', (err) => {
    // decide what to do
  });
});

// Close emitted after form parsed
form.on('close', () => {
  console.log('Upload completed!');
  res.setHeader('text/plain');
  res.end('Received ' + count + ' files');
});

// Parse req
form.parse(req);

// ...

If cb is provided, autoFields and autoFiles are set to true and all fields and files are collected and passed to the callback, removing the need to listen to any events on form. This is for convenience when you want to read everything, but be sure to write cleanup code, as this will write all uploaded files to the disk, even ones you may not be interested in.

form.parse(req, (err, fields, files) => {
  Object.keys(fields).forEach((name) => {
    console.log(`got field named ${name}`);
  });

  Object.keys(files).forEach((name) => {
    console.log(`got file named ${name}`);
  });

  console.log('Upload completed!');
  res.setHeader('text/plain');
  res.end(`Received ${files.length} files`);
});

fields is an object where the property names are field names and the values are arrays of field values.

files is an object where the property names are field names and the values are arrays of file objects.

form.bytesReceived

The amount of bytes received for this form so far.

form.bytesExpected

The expected number of bytes in this form.

Events

/**
 * Unless you supply a callback to `form.parse`, you definitely want to handle
 * this event. Otherwise your server *will* crash when users submit bogus
 * multipart requests!
 *
 * Only one `error` event can ever be emitted, and if an `error` event is
 * emitted, then `close` will not be emitted.
 *
 * If the error would correspond to a certain HTTP response code, the `err` object
 * will have a `statusCode` property with the value of the suggested HTTP response
 * code to send back.
 *
 * Note that an `error` event will be emitted both from the `form` and from the
 * current `part`.
 */
on(event: 'error', listener: (err: Error & { statusCode?: number }) => void): this;
/**
 * Emitted when a part is encountered in the request.
 * Parts for fields are not emitted when `autoFields` is on, and likewise parts
 * for files are not emitted when `autoFiles` is on.
 *
 * `part` emits 'error' events! Make sure you handle them.
 *
 * You *must* act on the part by reading it.
 * If you want to ignore it, just call `part.resume()`.
 */
on(event: 'part', listener: (part: PartEvent) => void): this;
/**
 * Emitted when the request is aborted. This event will be followed shortly
 * by an `error` event. In practice you do not need to handle this event.
 */
on(event: 'aborted', listener: () => void): this;
/**
 * Emitted when a chunk of data is received for the form. The `bytesReceived`
 * argument contains the total count of bytes received for this form so far. The
 * `bytesExpected` argument contains the total expected bytes if known, otherwise
 * `null`.
 */
on(event: 'progress', listener: (bytesReceived?: number, bytesExpected?: number) => void): this;
/**
 * Emitted after all parts have been parsed and emitted. Not emitted if an `error`
 * event is emitted.
 *
 * If you have `autoFiles` on, this is not fired until all the data has been
 * flushed to disk and the file handles have been closed.
 *
 * This is typically when you would send your response.
 */
on(event: 'close', listener: () => void): this;
/**
 * **By default multiparty will not touch your hard drive.** But if you add this
 * listener, multiparty automatically sets `form.autoFiles` to `true` and will
 * stream uploads to disk for you.
 *
 * **The max bytes accepted per request can be specified with `maxFilesSize`.**
 */
on(event: 'file', listener: (name?: string, file?: FormFile) => void): this;
/**
 * - `name` - field name.
 * - `value` - string field value.
 */
on(event: 'field', listener: (name?: string, value?: string) => void): this;

Where PartEvent and FormFile is:

interface PartEvent extends ReadableStream {
  /**
   * The headers for this part. For example, you may be interested in `content-type`.
   */
  headers: IncomingHttpHeaders;
  /**
   * The field name for this part.
   */
  name: string;
  /**
   * Only if the part is an incoming file.
   */
  filename: string;
  /**
   * The byte offset of this part in the request body.
   */
  byteOffset: number;
  /**
   * Assuming that this is the last part in the request, this is the size of this part in bytes.
   * You could use this, for example, to set the `Content-Length` header if uploading to S3.
   * If the part had a `Content-Length` header then that value is used here instead.
   */
  byteCount: number;
  on(event: 'error', listener: (err: Error & { statusCode?: number }) => void): this;
  resume(): this;
}

interface FormFile {
  /**
   * Same as `name` - the field name for this file.
   */
  fieldName: string;
  /**
   * The filename that the user reports for the file.
   */
  originalFilename: string;
  /**
   * The absolute path of the uploaded file on disk.
   */
  path: string;
  /**
   * The HTTP headers that were sent along with this file.
   */
  headers: IncomingHttpHeaders;
  /**
   * Size of the file in bytes.
   */
  size: number;
}

License

MIT