What is mime?
The mime npm package is a utility for handling and transforming file MIME types. It provides functionality to lookup the MIME type for a file based on its extension, determine the default extension for a MIME type, and define custom MIME type mappings.
What are mime's main functionalities?
Lookup MIME type by extension
This feature allows you to get the MIME type for a given file extension. In the code sample, we are looking up the MIME type for a '.json' file, which returns 'application/json'.
const mime = require('mime');
const mimeType = mime.getType('json'); // 'application/json'
Lookup extension by MIME type
This feature enables you to find the default file extension for a given MIME type. In the code sample, we are finding the extension for the MIME type 'application/json', which returns 'json'.
const mime = require('mime');
const extension = mime.getExtension('application/json'); // 'json'
Define custom MIME type mappings
This feature allows you to define custom MIME type mappings. In the code sample, we are adding a custom MIME type 'text/x-some-format' with multiple extensions. The second argument 'true' indicates that the custom types should take precedence over the built-in types.
const mime = require('mime');
mime.define({ 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'] }, true);
Other packages similar to mime
mime-types
The 'mime-types' package is similar to 'mime' in that it provides MIME type lookup based on file extension and vice versa. It is based on the mime-db dataset, which is a comprehensive dataset of MIME types compiled from various sources. Compared to 'mime', it might offer a more extensive and updated list of MIME types.
file-type
The 'file-type' package goes beyond simple MIME type lookup by extension; it can detect the actual MIME type of a file or a Buffer by checking the file's magic numbers (file signatures). This can be more reliable than 'mime' when dealing with files that have incorrect or missing extensions.
A library for doing simple mime-type lookups.
var mime = require('mime');
mime.lookup('/path/to/file.txt'); // => 'text/plain'
mime.lookup('file.txt'); // => 'text/plain'
mime.lookup('.txt'); // => 'text/plain'
mime.lookup('htm'); // => 'text/html'
... and extension lookups by mime-type
mime.extension('text/html'); // => 'html'
mime.extension('application/octet-stream'); // => 'bin'
It also includes rudimentary logic for determining charsets. (Useful in a web
framework):
mime.charset.lookup('text/plain'); // => 'UTF-8'
Install with npm:
npm install mime