mime-types npm

 

The mime-types package is a Node.js module that provides a utility for working with MIME types. It is designed to be a comprehensive and reliable tool for determining the content type of files based on their extensions. This package is widely used in the JavaScript ecosystem and is available through the npm registry.

Installation

To install the mime-types package, you can use the npm install command:

$ npm install mime-types

This will download and install the package and its dependencies.

API Overview

The mime-types package provides several functions to work with MIME types. Here are some of the key functions:

mime.lookup(path)

This function looks up the content type associated with a file based on its extension. If the extension is not recognized, it returns false.

const mime = require('mime-types');

console.log(mime.lookup('json')); // 'application/json'
console.log(mime.lookup('.md')); // 'text/markdown'
console.log(mime.lookup('file.html')); // 'text/html'
console.log(mime.lookup('folder/file.js')); // 'application/javascript'
console.log(mime.lookup('folder/.htaccess')); // false
console.log(mime.lookup('cats')); // false

mime.contentType(type)

This function creates a full content-type header given a content-type or extension. If an extension is provided, mime.lookup is used to get the matching content-type. If the content-type does not already have a charset parameter, mime.charset is used to get the default charset and add it to the returned content-type.

console.log(mime.contentType('markdown')); // 'text/x-markdown; charset=utf-8'
console.log(mime.contentType('file.json')); // 'application/json; charset=utf-8'
console.log(mime.contentType('text/html')); // 'text/html; charset=utf-8'
console.log(mime.contentType('text/html; charset=iso-8859-1')); // 'text/html; charset=iso-8859-1'

mime.extension(type)

This function gets the default extension for a given content-type.

console.log(mime.extension('application/octet-stream')); // 'bin'

mime.charset(type)

This function looks up the implied default charset of a content-type.

console.log(mime.charset('text/markdown')); // 'UTF-8'

Adding Types

All MIME types used by the mime-types package are based on the mime-db package. If you want to add new MIME types, you need to open a pull request in the mime-db repository.

License

The mime-types package is licensed under the MIT License.

By using the mime-types package, you can easily handle MIME type lookups and content-type header creation in your Node.js applications. This package is highly reliable and widely used, making it a great choice for managing MIME types.

posted on 2025-12-23 16:18  漫思  阅读(3)  评论(0)    收藏  举报

导航