Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท util, assert and the Test Runner

Node.js util.MIMEType class

Reference for util.MIMEType and MIMEParams in Node.js: parse Content-Type strings, read type, subtype and essence, and edit parameters like charset.

util.MIMEType parses and builds MIME types, the type/subtype; parameter=value strings used in Content-Type headers and file formats. Instead of splitting strings yourself, you get the parts as properties and a normalized string back.

A MIMEType has type, subtype, essence (the two joined) and params, a MIMEParams object that works like a small map. Parsing lower-cases the type and subtype and follows the WHATWG MIME Sniffing rules, so it behaves like browsers do.

NODE
import { MIMEType } from "node:util";

const mime = new MIMEType("text/html; charset=utf-8");
console.log(mime.essence); // "text/html"

Try it

Node.js Reading a Content-Type value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Editing and handling bad input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
new util.MIMEType(input: string)
mime.type: string
mime.subtype: string
mime.essence: string      // read-only
mime.params: MIMEParams
mime.toString(): string

MIMEParams methods: get(name), set(name, value), has(name), delete(name), entries(), keys(), values() and iteration with for...of (pairs of name and value).

Name Description
input The MIME type text to parse. Whitespace around parts is tolerated.

Returns: a MIMEType instance. toString(), toJSON() and string conversion give the serialized form without extra spaces: text/html;charset=utf-8.

Errors: an unparsable input throws ERR_INVALID_MIME_SYNTAX. Setting type or subtype to an invalid token throws the same error.

Usage notes

  • essence ignores parameters, so it is the right value to compare against "application/json".
  • Type, subtype and parameter names are lower-cased. Parameter values keep their case.
  • Serialization has no space after ;. Compare parsed objects, not raw strings.
  • A value that is not a plain token is written in double quotes automatically.
  • Parameters keep the order in which they were added.
  • It parses; it does not know which MIME type fits a file extension. Keep your own lookup table for that.
  • MIMEType is exported from node:util. Check the stability notes of your Node version, because the class is newer than most of util.