@szymmis/multipart
TypeScript icon, indicating that this package has built-in type declarations

1.4.1 • Public • Published

⚙️ @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
Content-Type: multipart/form-data; boundary=... for this middleware to work.
Such Content-Type is set automatically when you submit your form on the front-end or when you set the body of your request as a FormData

Example of front-end code for sending FormData over the fetch request

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>

An object containing all non-file form fields values from inputs of type text, number, etc.

    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

Package Sidebar

Install

npm i @szymmis/multipart

Weekly Downloads

35

Version

1.4.1

License

MIT

Unpacked Size

12 kB

Total Files

5

Last publish

Collaborators

  • szymmis