npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ts-stack/multer

v1.0.0

Published

Multer is a node.js parser for handling `multipart/form-data`, which is primarily used for uploading files.

Downloads

122

Readme

@ts-stack/multer

Is a node.js library for handling multipart/form-data, which is primarily used for uploading files. It is fork of ExpressJS multer v2.0.0-rc.4.

NOTE: Multer will not process any form which is not multipart (multipart/form-data).

Installation

npm install @ts-stack/multer

Usage

Multer returns an object in Promise with four properties: textFields, file, files and groups. The textFields object contains the values of the text fields of the form, the file, files or groups object contains the files (as Readable stream) uploaded via the form.

The following example uses ExpressJS only for simplicity. In fact, @ts-stack/multer does not return middleware, so it is less convenient for ExpressJS than the original module. Basic usage example:

import { Multer } from '@ts-stack/multer';
import express from 'express';
import { createWriteStream } from 'node:fs';

// Here `avatar`, `photos` and `gallery` - is the names of the field in the HTML form.
const multer = new Multer({ limits: { fileSize: '10MB' } });
const parseAvatar = multer.single('avatar');
const parsePhotos = multer.array('photos', 12);
const parseGroups = multer.groups([
  { name: 'avatar', maxCount: 1 },
  { name: 'gallery', maxCount: 8 },
]);
const app = express();

app.post('/profile', async (req, res, next) => {
  const parsedForm = await parseAvatar(req, req.headers);
  // parsedForm.file is the `avatar` file
  // parsedForm.textFields will hold the text fields, if there were any
  const path = `uploaded-files/${parsedForm.file.originalName}`;
  const writableStream = createWriteStream(path);
  parsedForm.file.stream.pipe(writableStream);
  // ...
});

app.post('/photos/upload', async (req, res, next) => {
  const parsedForm = await parsePhotos(req, req.headers);
  // parsedForm.files is array of `photos` files
  // parsedForm.textFields will contain the text fields, if there were any
  const promises: Promise<void>[] = [];
  parsedForm.files.forEach((file) => {
    const promise = new Promise<void>((resolve, reject) => {
      const path = `uploaded-files/${file.originalName}`;
      const writableStream = createWriteStream(path);
      writableStream.on('error', reject);
      writableStream.on('finish', resolve);
      file.stream.pipe(writableStream);
    });
    promises.push(promise);
  });

  await Promise.all(promises);
  // ...
});

app.post('/cool-profile', async (req, res, next) => {
  const parsedForm = await parseGroups(req, req.headers);
  // parsedForm.groups is an object (String -> Array) where fieldname is the key, and the value is array of files
  //
  // e.g.
  //  parsedForm.groups['avatar'][0] -> File
  //  parsedForm.groups['gallery'] -> Array
  //
  // parsedForm.textFields will contain the text fields, if there were any
});

In case you need to handle a text-only multipart form, you can use the .textFields() method, example:

import { Multer } from '@ts-stack/multer';
import express from 'express';

const parseFormFields = new Multer().textFields();
const app = express();

app.post('/profile', async (req, res, next) => {
  const parsedForm = await parseFormFields(req, req.headers);
  // parsedForm.textFields contains the text fields
});

Error handling

This is a list of error codes:

const errorMessages = new Map<ErrorMessageCode, string>([
  ['CLIENT_ABORTED', 'Client aborted'],
  ['LIMIT_FILE_SIZE', 'File too large'],
  ['LIMIT_FILE_COUNT', 'Too many files'],
  ['LIMIT_FIELD_KEY', 'Field name too long'],
  ['LIMIT_FIELD_VALUE', 'Field value too long'],
  ['LIMIT_FIELD_COUNT', 'Too many fields'],
  ['LIMIT_UNEXPECTED_FILE', 'Unexpected file field'],
]);

You can see these error codes in the MulterError#code property:

import { Multer, MulterError, ErrorMessageCode } from '@ts-stack/multer';

// ...
try {
  const parse = new Multer().single('avatar');
  const parsedForm = await parse(req, req.headers);
  // ...
} catch (err) {
  if (err instanceof MulterError) {
    err.code; // This property is of type ErrorMessageCode.
    // ...
  }
}