CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mime

A comprehensive library for mime-type mapping

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

custom-instances.mddocs/

Custom MIME Instances

Create and configure custom MIME instances with your own type definitions, perfect for specialized applications, custom file types, or when you need mutable MIME type mappings.

Capabilities

Mime Class Constructor

Creates a new mutable MIME instance with optional initial type definitions.

/**
 * Create a new custom mime instance
 * @param args - Optional TypeMap objects to define initial mappings
 */
class Mime {
  constructor(...args: TypeMap[]);
}

type TypeMap = { [key: string]: string[] };

Usage Examples:

import { Mime } from "mime";

// Empty instance (no initial types)
const customMime = new Mime();

// Instance with predefined types from mime databases
import standardTypes from "mime/types/standard.js";
import otherTypes from "mime/types/other.js";

const fullMime = new Mime(standardTypes, otherTypes);

// Instance with custom types only
const appMime = new Mime({
  "application/x-custom": ["custom", "cust"],
  "text/x-special": ["special"]
});

// Combining standard and custom types
const hybridMime = new Mime(standardTypes, {
  "application/x-myapp": ["myapp", "ma"]
});

Define Custom Type Mappings

Add or modify MIME type to extension mappings on custom instances.

/**
 * Define mimetype -> extension mappings
 * @param typeMap - Object mapping MIME types to extension arrays
 * @param force - Override existing mappings if true (default: false)
 * @returns The Mime instance for chaining
 */
define(typeMap: TypeMap, force?: boolean): this;

Usage Examples:

import { Mime } from "mime";

const customMime = new Mime();

// Define new type mappings
customMime.define({
  "application/x-config": ["config", "cfg"],
  "text/x-log": ["log", "logfile"]
});

// Test the custom mappings
customMime.getType("app.config");        // "application/x-config"
customMime.getExtension("text/x-log");   // "log"

// Chain multiple definitions
customMime
  .define({ "application/x-data": ["data"] })
  .define({ "text/x-notes": ["notes", "note"] });

Force Override Example:

const customMime = new Mime();

// Initial definition
customMime.define({ "text/x-special": ["special"] });

// This would throw an error (extension conflict)
try {
  customMime.define({ "application/special": ["special"] });
} catch (error) {
  console.log(error.message); 
  // "application/special -> special" conflicts with "text/x-special -> special". 
  // Pass `force=true` to override this definition.
}

// Force override existing mapping
customMime.define({ "application/special": ["special"] }, true);
customMime.getType("file.special"); // "application/special" (overridden)

Instance Methods

Custom instances have the same interface as default instances.

/**
 * Get mime type associated with an extension or file path
 */
getType(path: string): string | null;

/**
 * Get default file extension associated with a mime type
 */
getExtension(type: string): string | null;

/**
 * Get all file extensions associated with a mime type
 */
getAllExtensions(type: string): Set<string> | null;

Type Database Imports

Standard Types Database

import standardTypes from "mime/types/standard.js";

// Contains official, widely-supported MIME types
// Examples: text/html, application/json, image/png, etc.
const mime = new Mime(standardTypes);

Other Types Database

import otherTypes from "mime/types/other.js";

// Contains vendor-specific and experimental types
// Examples: application/vnd.*, application/x-*, etc.
const mime = new Mime(otherTypes);

Combined Database (Full MIME compatibility)

import { Mime } from "mime";
import standardTypes from "mime/types/standard.js";
import otherTypes from "mime/types/other.js";

// Equivalent to the default mime instance
const customMime = new Mime(standardTypes, otherTypes);

TypeMap Format

Basic TypeMap Structure

type TypeMap = { [key: string]: string[] };

// Example TypeMap
const myTypes: TypeMap = {
  "application/x-myformat": ["myf", "myformat"],
  "text/x-config": ["config", "cfg", "conf"],
  "image/x-custom": ["xcust"]
};

Extension Priority

The first extension in the array becomes the default:

const customMime = new Mime();
customMime.define({
  "image/custom": ["primary", "secondary", "alt"]
});

customMime.getExtension("image/custom");     // "primary" (first = default)
customMime.getAllExtensions("image/custom"); // Set(3) { "primary", "secondary", "alt" }

Starred Extensions

Extensions starting with * are not eligible to be the default extension:

const customMime = new Mime();
customMime.define({
  "application/special": ["*rare", "common", "std"]
});

customMime.getExtension("application/special"); // "common" (first non-starred)
customMime.getType("file.rare");                // "application/special" (still maps back)

Default Instance Limitations

Important: The default mime instances are immutable and cannot be modified:

import mime from "mime";

// This will throw an error
try {
  mime.define({ "custom/type": ["custom"] });
} catch (error) {
  console.log(error.message);
  // "define() not allowed for built-in Mime objects. 
  // See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances"
}

Solution: Always create custom instances for modification:

import { Mime } from "mime";
import standardTypes from "mime/types/standard.js";

// Create mutable version of default instance
const mutableMime = new Mime(standardTypes)
  .define({ "custom/type": ["custom"] });

Advanced Patterns

Application-Specific MIME Types

import { Mime } from "mime";

// Create app-specific MIME instance
const appMime = new Mime({
  "application/x-myapp-config": ["myconfig"],
  "application/x-myapp-template": ["mytemplate", "tpl"],
  "application/x-myapp-data": ["mydata", "dat"]
});

// Use in application
function processFile(filename: string) {
  const mimeType = appMime.getType(filename);
  switch (mimeType) {
    case "application/x-myapp-config":
      return processConfig(filename);
    case "application/x-myapp-template":
      return processTemplate(filename);
    default:
      return processGeneric(filename);
  }
}

Fallback Pattern

import mime from "mime";
import { Mime } from "mime";

// Custom instance with fallback to default
const customMime = new Mime({
  "application/x-special": ["special"]
});

function getMimeType(filename: string): string | null {
  // Try custom types first
  let type = customMime.getType(filename);
  if (type) return type;
  
  // Fallback to default mime database
  return mime.getType(filename);
}

Error Handling

const customMime = new Mime();

// Extension conflicts throw errors unless force=true
try {
  customMime.define({ "text/plain": ["txt"] });     // OK
  customMime.define({ "text/custom": ["txt"] });    // Throws: extension conflict
} catch (error) {
  console.log("Conflict detected:", error.message);
  
  // Resolve with force flag
  customMime.define({ "text/custom": ["txt"] }, true);
}

// Invalid inputs return null (same as default instances)
customMime.getType(null);                          // null
customMime.getExtension("");                       // null

docs

cli.md

custom-instances.md

index.md

mime-operations.md

tile.json