Parse, serialize, and manipulate MIME types
This package will parse MIME types into a structured format, which can then be manipulated and serialized:
const MIMEType = ;const mimeType = `Text/HTML;Charset="utf-8"`;console;console;console;console;console;mimeTypeparameters;console;console;console;console;
This package's main module's default export is a class,
MIMEType. Its constructor takes a string which it will attempt to parse into a MIME type; if parsing fails, an
Error will be thrown.
parse() static factory method
As an alternative to the constructor, you can use
MIMEType.parse(string). The only difference is that
parse() will return
null on failed parsing, whereas the constructor will throw. It thus makes the most sense to use the constructor in cases where unparseable MIME types would be exceptional, and use
parse() when dealing with input from some unconstrained source.
type: the MIME type's type, e.g.
subtype: the MIME type's subtype, e.g.
essence: the MIME type's essence, e.g.
parameters: an instance of
MIMETypeParameters, containing this MIME type's parameters
subtype can be changed. They will be validated to be non-empty and only contain HTTP token code points.
essence is only a getter, and cannot be changed.
parameters is also a getter, but the contents of the
MIMETypeParameters object are mutable, as described below.
toString()serializes the MIME type to a string
isHTML(): returns true if this instance represents a HTML MIME type
isXML(): returns true if this instance represents an XML MIME type
allowParameterscan be set to true to allow arbitrary parameters, instead of their presence causing the method to return
MIMETypeParameters class, instances of which are returned by
MIMETypeParameters methods will always interpret their arguments as appropriate for MIME types, so e.g. parameter names will be lowercased, and attempting to set invalid characters will throw.
const mimeType = `x/x;a=b;c=D;E="F"`;// Logs:// a b// c D// e Ffor const name value of mimeTypeparametersconsole;console;console;console;mimeTypeparameters;console;console;// Throws:mimeTypeparameters;
Raw parsing/serialization APIs
If you want primitives on which to build your own API, you can get direct access to the parsing and serialization algorithms as follows:
const parse = ;const serialize = ;
parse(string) returns an object containing the
subtype strings, plus
parameters, which is a
Map. This is roughly our equivalent of the spec's MIME type record. If parsing fails, it instead returns
serialize(record) operates on the such an object, giving back a string according to the serialization algorithm.