undici exposes helpers for parsing and serializing MIME types according to the
WHATWG MIME Sniffing Standard. These are the same primitives undici uses
internally to interpret Content-Type headers and data: URLs.
Import the functions from 'undici':
import { parseMIMEType, serializeAMimeType } from 'undici'A parsed MIME type is represented as a plain object with the following shape:
parseMIMEType(input): Object | string<string>'failure'
when
input
cannot be parsed.Implements the WHATWG parse a MIME type algorithm. The type and subtype
are lowercased, and only the first occurrence of a duplicate parameter name is
retained. When input is empty, lacks a /, or otherwise violates the grammar,
the string literal 'failure' is returned instead of a record.
import { parseMIMEType } from 'undici'
parseMIMEType('text/html; charset=gbk')
// {
// type: 'text',
// subtype: 'html',
// parameters: Map(1) { 'charset' => 'gbk' },
// essence: 'text/html'
// }
parseMIMEType('not a mime type')
// 'failure'serializeAMimeType(mimeType): string<string>Implements the WHATWG serialize a MIME type algorithm. The essence is
emitted followed by each parameter as ;name=value. A parameter value that
contains characters outside the HTTP token set is quoted, and any " or \
characters within it are escaped.
import { serializeAMimeType } from 'undici'
serializeAMimeType({
type: 'text',
subtype: 'html',
parameters: new Map([['charset', 'gbk']]),
essence: 'text/html'
})
// 'text/html;charset=gbk'