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

multermate-es

v1.0.1

Published

A robust and flexible file upload utility built on top of Multer, providing advanced file handling capabilities for Node.js applications.

Downloads

142

Readme

Multer Mate

A robust and flexible file upload utility built on top of Multer, providing advanced file handling capabilities for Node.js applications.

Features

  • 📁 Flexible file storage configuration
  • 🔒 Built-in file type validation
  • 📦 Single and multiple file uploads
  • 🎯 Field-specific file type restrictions
  • 🗑️ File deletion utility
  • ⚡ Configurable file size limits
  • 🎨 Custom MIME type support
  • 🔄 Unique file naming with UUID
  • 🛡️ Path sanitization
  • 📝 Comprehensive error handling

Installation

npm install multermate

Basic Usage

import { uploadSingle, uploadMultiple, deleteFile } from "multermate-es";

Upload Configurations

Single File Upload

// Basic single file upload
app.post("/upload", uploadSingle(), (req, res) => {
  res.json({ file: req.file });
});

// Advanced single file upload
app.post(
  "/upload/advanced",
  uploadSingle({
    destination: "uploads/images",
    filename: "profile",
    fileTypes: ["images"],
    fileSizeLimit: 5 * 1024 * 1024, // 5MB
    preservePath: false,
  }),
  (req, res) => {
    res.json({ file: req.file });
  }
);

Multiple Files Upload

// Multiple fields with different configurations
app.post(
  "/upload/multiple",
  uploadMultiple({
    fields: [
      {
        name: "avatar",
        maxCount: 1,
        fileTypes: ["images"],
      },
      {
        name: "documents",
        maxCount: 5,
        fileTypes: ["pdfs"],
      },
      {
        name: "media",
        maxCount: 3,
        fileTypes: ["images", "videos"],
      },
    ],
    destination: "uploads/mixed",
    fileSizeLimit: 10 * 1024 * 1024, // 10MB per file
  }),
  (req, res) => {
    res.json({ files: req.files });
  }
);

Custom MIME Types

app.post(
  "/upload/custom",
  uploadSingle({
    destination: "uploads/custom",
    customMimeTypes: [
      "application/vnd.ms-excel",
      "application/json",
      "text/csv",
    ],
    fileSizeLimit: 1024 * 1024, // 1MB
  })
);

File Deletion

// Simple file deletion
app.delete("/files/:filename", async (req, res) => {
  const isDeleted = await deleteFile(`uploads/${req.params.filename}`);
  res.json({ success: isDeleted });
});

// Advanced file deletion with error handling
app.delete("/files/:type/:filename", async (req, res) => {
  try {
    const filePath = path.join("uploads", req.params.type, req.params.filename);
    const isDeleted = await deleteFile(filePath);

    if (isDeleted) {
      res.json({
        success: true,
        message: "File deleted successfully",
      });
    } else {
      res.status(404).json({
        success: false,
        message: "File not found or unable to delete",
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message,
    });
  }
});

API Reference

uploadSingle(options)

Configures single file upload with the following options:

| Option | Type | Default | Description | | --------------- | -------- | --------- | ---------------------- | | destination | string | 'uploads' | Upload directory path | | filename | string | 'file' | Form field name | | fileTypes | string[] | ['all'] | Allowed file types | | customMimeTypes | string[] | [] | Custom MIME types | | fileSizeLimit | number | 50MB | Max file size in bytes | | preservePath | boolean | false | Preserve original path |

uploadMultiple(options)

Configures multiple file uploads with the following options:

| Option | Type | Default | Description | | --------------- | -------- | --------- | -------------------- | | fields | Field[] | [] | Field configurations | | destination | string | 'uploads' | Upload directory | | customMimeTypes | string[] | [] | Custom MIME types | | fileSizeLimit | number | 50MB | Max file size | | preservePath | boolean | false | Preserve paths |

Field Configuration

| Option | Type | Default | Description | | --------- | -------- | ------- | --------------------- | | name | string | - | Field name (required) | | maxCount | number | 10 | Max files per field | | fileTypes | string[] | ['all'] | Allowed types |

deleteFile(filePath)

Deletes a file from the filesystem:

| Parameter | Type | Description | | --------- | ---------------- | ---------------- | | filePath | string | Path to file | | Returns | Promise | Deletion success |

Supported File Types

const ALLOWED_MIME_TYPES = {
  images: ["image/jpeg", "image/jpg", "image/png", "image/gif"],
  videos: ["video/mp4", "video/mpeg", "video/ogg", "video/webm", "video/avi"],
  pdfs: ["application/pdf"],
  all: [
    /* combination of all above types */
  ],
};

Error Handling

app.post("/upload", uploadSingle(), (req, res) => {
  try {
    // File size validation
    if (req.fileValidationError) {
      return res.status(400).json({
        error: req.fileValidationError,
      });
    }

    // File existence check
    if (!req.file) {
      return res.status(400).json({
        error: "No file uploaded",
      });
    }

    // Success response
    res.json({
      success: true,
      file: {
        filename: req.file.filename,
        path: req.file.path,
        size: req.file.size,
        mimetype: req.file.mimetype,
      },
    });
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});

Best Practices

  1. Always implement proper error handling
  2. Set appropriate file size limits
  3. Validate file types on the server
  4. Use custom storage destinations for different file types
  5. Implement file cleanup mechanisms
  6. Consider implementing file type verification beyond MIME types

License

MIT

Contributing

Contributions are welcome! Please feel free to submit issues and pull requests.

Author

Your Name

Support

For support, please open an issue in the GitHub repository.