Skip to content
JavaScript Basics: Read and Update MIME Parameters

JavaScript Basics: Read and Update MIME Parameters

October 30, 2026

A Content-Type value contains a media type plus optional parameters. Splitting on semicolons is fragile because a quoted parameter can contain a semicolon itself. Node’s MIMEType provides structured access without writing that parser yourself.

Prepare a scratch directory

Tested on Linux with Node.js v24.19.0. You need Node, Bash, a text editor, and the standard mktemp, rm, and rmdir utilities. No npm packages or remote services are needed. The .mjs extension selects ES modules.

Keep using the same terminal. Stop if setup fails, before saving the source:

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Run the example

Save this as inspect-mime.mjs:

import assert from 'node:assert/strict';
import { MIMEType } from 'node:util';

const mime = new MIMEType('Text/Plain; Charset=UTF-8; note="a;b"');
assert.equal(mime.essence, 'text/plain');
assert.equal(mime.params.get('charset'), 'UTF-8');
assert.equal(mime.params.get('note'), 'a;b');
console.log('Media type:', mime.essence);
console.log('Charset:', mime.params.get('charset'));
console.log('Quoted parameter:', mime.params.get('note'));

mime.params.set('charset', 'utf-8');
mime.params.delete('note');
assert.equal(String(mime), 'text/plain;charset=utf-8');
console.log('Updated:', String(mime));
assert.throws(() => new MIMEType('not a type'), TypeError);
console.log('Invalid media type: rejected');

Run it:

node inspect-mime.mjs

Observed output:

Media type: text/plain
Charset: UTF-8
Quoted parameter: a;b
Updated: text/plain;charset=utf-8
Invalid media type: rejected

Read the result

Parsing normalizes the type and parameter names to lowercase, but the parameter value UTF-8 stays as supplied. Read known parameters using their normalized names. Updating the charset and deleting the demonstration parameter changes the serialized result without rebuilding the entire header by hand.

The constructor rejects an invalid media type, as the assertion demonstrates. Do not mistake successful parsing for validation of the actual body: the declared type may disagree with its bytes. This is a parser for one MIME type, not for an HTTP Accept list or a whole MIME message. Serialization may normalize spacing and casing, so preserve the original string separately when exact original formatting matters.

The official Node.js reference describes the API. The assertions above check the specific fixture and its intended edge case.

Clean up

Remove the source and then the empty practice directory:

rm -- inspect-mime.mjs
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

If the directory is not empty, inspect the remaining files rather than deleting unknown contents.

Acknowledgements

This post was created with assistance from AI.

Last updated on