MIME Type Utility

3.0.2 · active · verified Sun Apr 19

mime-types is a JavaScript utility library for working with content-types, offering functions to look up MIME types, file extensions, and associated charsets. Currently at stable version `3.0.2`, the package primarily focuses on providing accurate MIME type data sourced from `mime-db`. It differentiates itself from older `mime` modules by explicitly returning `false` for unknown types (rather than a naive fallback), avoiding instance creation (`new Mime()`), and omitting `.define()` functionality. While its core API remains compatible with `mime@1.x`, it's maintained by the `jshttp` organization and generally receives updates driven by new MIME types or minor fixes rather than frequent new features. A key aspect is its `mime-db` dependency; programmatic API changes are considered semver, but updates to the underlying MIME type data itself are not, meaning users needing strict data versioning must manage `mime-db` via package manager overrides.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates core `mime-types` functionalities: `lookup` for MIME types, `contentType` for full headers, `extension` for default extensions, and `charset` for implied charsets, including handling unknown types.

import mime from 'mime-types';
import path from 'path';

// Look up a MIME type by file extension or path
const jsonType = mime.lookup('json');
console.log(`JSON type: ${jsonType}`); // Expected: application/json

const markdownType = mime.lookup('.md');
console.log(`Markdown type: ${markdownType}`); // Expected: text/markdown

const filePath = '/path/to/document.pdf';
const fileType = mime.lookup(filePath);
console.log(`File type for '${filePath}': ${fileType}`); // Expected: application/pdf

// Handle unknown types (returns false)
const unknownType = mime.lookup('unrecognized');
const fallbackType = unknownType || 'application/octet-stream';
console.log(`Unknown type lookup: ${fallbackType}`); // Expected: application/octet-stream

// Create a full Content-Type header
const htmlContentType = mime.contentType('text/html');
console.log(`HTML Content-Type: ${htmlContentType}`); // Expected: text/html; charset=utf-8

const jsContentType = mime.contentType(path.extname('app.js'));
console.log(`JS Content-Type: ${jsContentType}`); // Expected: application/javascript; charset=utf-8

// Get default extension for a MIME type
const binExtension = mime.extension('application/octet-stream');
console.log(`Extension for octet-stream: ${binExtension}`); // Expected: bin

// Lookup implied default charset
const textCharset = mime.charset('text/plain');
console.log(`Charset for text/plain: ${textCharset}`); // Expected: UTF-8

view raw JSON →