Mime Entries
mime-entries
is a utility for handling and converting between MIME types and file extensions.
It provides a simple interface to fetch MIME types based on file extensions and vice versa. This can be particularly useful in scenarios where you need to determine the MIME type of a file using the name or path, based on their extension.
It uses mime-db as references for MIME types and file extensions.
Installation
npm install mime-entries
(You can also use yarn
or pnpm
instead of npm
)
Usage
import { getMimeType, getExtension } from 'mime-entries';
const mimeEntries = new MimeEntries();
const types = mimeEntries.getTypesByExtension('.txt');
console.log(types);
const extensions = mimeEntries.getAllExtensions('text/plain');
console.log(extensions);
const entryByType = mimeEntries.getMimeEntry('text/plain');
console.log(entryByType);
const entriesByExt = mimeEntries.getMimeEntriesByExt('.txt');
console.log(entriesByExt);
It is also possible to add custom types and extensions to the instance.
import { MimeEntries } from 'mime-entries';
const database = new MimeEntries(
{"text/x-python" : {"extensions": ["py"],"compressible": true}}
);
const entriesByExt = database.getMimeEntriesByExt('.py');
console.log(entriesByExt);
API
getTypesByExtension(extension: string): Set<string> | undefined
Returns a set of MIME types for a given file extension.
database.getTypesByExtension("txt")
database.getTypesByExtension(".json")
database.getTypesByExtension("js")
database.getTypesByExtension("dir/text.txt")
database.getTypesByExtension("dir\\text.txt")
database.getTypesByExtension(".txt.txt")
database.getTypesByExtension(".txt")
undefined
is returned if the extension is not found.
database.getTypesByExtension("unknown")
And an error is thrown if the extension is empty or invalid.
database.getTypesByExtension(" ")
getAllExtensions(type: string): Set<string> | undefined
Returns a set of file extensions for a given MIME type.
database.getAllExtensions("text/plain")
database.getAllExtensions("application/json")
getMimeEntry(type: string): MimeEntry | undefined
Just an alias of this.database[type]
.
database.getMimeEntry("text/plain")
getMimeEntriesByExt(extension: string): {[type: string]: MimeEntry} | undefined
Returns a map of MIME entries for a given file extension.
database.getMimeEntriesByExt("txt")
database.getMimeEntriesByExt("js")
getMainTypeByExt(extension: string): Set<string> | undefined
Returns a set of main MIME types for a given file extension.
Main is the first part of the MIME type, e.g. text
in text/plain
.
database.getMainTypeByExt("txt")
database.getMainTypeByExt("js")
Credit & Thanks
I was heavily inspired by mime but wanted to add some function. I ended up to write my own version, hopefully more understandable and with more features than mime.
Contributing
The package use commit-and-tag-version for release, so please follow the Conventional Commits specification.
Don't forget to update the tests before submitting a PR!