Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Socket
Sign inDemoInstall

@szymmis/multipart

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@szymmis/multipart

Simple lightweight multipart/form-data express middleware


Version published
Maintainers
1
Created
Source

⚙️ @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

namedescriptiondefaultvalid valuesexample value
limitMaximum payload size10mb{number}kb/mb50mb

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 ...>;
}
fielddescriptionexample
filenameUploaded file's namedata.txt
extensionUploaded file's extensiontxt
typeMIME typetext/plain
dataNode.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

Keywords

FAQs

Package last updated on 08 Jan 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc