Skip to content

szymmis/multipart

Repository files navigation

⚙️ @szymmis/multipart

multipart/form-data parsing middleware for @expressjs

bundle-size downloads-per-week npm

✨ Key features

  • Written in TypeScript
  • Works with CommonJS and ESModules import syntax
  • Tests written for all use cases
  • express is the only runtime dependencies
  • Only ~1kB in size when minified

💬 Introduction

Using express middleware for transforming json or parsing cookies is super easy and requires minimal configuration, so why parsing multipart/form-data should be different? Plug in the middleware and let it handle the request, while all you have to do is to utilize Request param populated with fields and files from the request.

//server.js
const express = require("express");
const multipart = require("@szymmis/multipart");

const app = express();
app.use(multipart());

app.post("/upload", (req, res) => {
  console.log(req.fields);
  console.log(req.files);
});

Perfect, when all you want is to have form data parsed in a convenient form, without unnecessary disk saves, e.g. parsing CSV sent over the network and sending JSON back. No redundant calls as the parser runs only when the Content-Type header's value is set to multipart/form-data.

📦 Installation and usage

  • Install the package with your favorite package manager
 $ yarn add @szymmis/multipart
  • Import and register as a middleware
//server.ts
import express from "express";
import multipart from "@szymmis/multipart";

const app = express();
app.use(multipart());
  • Utilize request object populated with fields and files
//server.ts
import express from "express";
import multipart from "@szymmis/multipart"

const app = express();
app.use(multipart());

app.post("/upload", (req, res) => {
  console.log(req.fields);
  //Example output:
  {
    name: "John",
    surname: "Doe",
    age: "32"
  }

  console.log(req.files);
  //Example output:
  {
    file: {
      filename: "file.txt",
      extension: "txt",
      type: "text/plain"
      data: <Buffer ...>
    }
  }
})

⚠️ Note ⚠️

The Content-Type header of the request must be in form of multipart/form-data; boundary=... for this middleware to work. It's set automatically when you submit form on the client-side or when you set the body of your request as a FormData

Working client-side fetch example

const form = document.querySelector("#form-id");
form.onsubmit = (e) => {
  e.preventDefault(); // prevent page reload on submit
  const fd = new FormData(form);
  fetch("http://localhost:3000/upload", { method: "POST", body: fd });
};

🔧 Options

name description default valid values example value
limit Maximum payload size 10mb {number}kb/mb 50mb

You can specify options object when registering the middleware

app.use(
  multipart({
    /*Your options go here */
  })
);

For example:

app.use(multipart({ limit: "50mb" }));

📝 Documentation

req.fields: Record<string, string>

A dictionary of all non-file form fields in form of field name - value pairs.

    console.log(req.fields)
    // Example output:
    {
        name: "John",
        surname: "Doe",
        age: "32"
    }

req.files: Record<string, FormDataFile>

A dictionary of all the type="file" fields in form

    console.log(req.files)
    // Example output:
    {
        invoice: {
            filename: "my_invoice.pdf",
            extension: "pdf",
            type: "application/pdf",
            data: <Buffer ...>
        }
    }

Where each file is an object of type FormDataFile

interface FormDataFile {
  filename: string;
  extension: string;
  type: string;
  data: <Buffer ...>;
}
field description example
filename Uploaded file's name data.txt
extension Uploaded file's extension txt
type MIME type text/plain
data Node.js Buffer containing raw data as bytes <Buffer ...>

🤔 Buffer containing what?

You can easily transform Buffer into string using its toString() method

const { file } = req.files;
console.log(file?.data.toString());

Or save the file onto the disk using node fs module

const fs = require("fs");
//...
app.post("/", (req, res) => {
  const { logs } = req.files;
  fs.writeFileSync("output.txt", logs?.data);
  //...
});

⚖️ License

MIT

🖥️ Credits

@szymmis