0
# Raw APIs
1
2
Low-level parsing and serialization functions providing direct access to the WHATWG MIME Sniffing Standard algorithms. These APIs are useful for building custom MIME type handling implementations.
3
4
## Capabilities
5
6
### Parse Function
7
8
Raw parsing function that converts MIME type strings into structured objects.
9
10
```javascript { .api }
11
/**
12
* Parses a MIME type string into a structured object
13
* @param {string} input - MIME type string to parse
14
* @returns {Object|null} MIME type record object or null if parsing fails
15
* @returns {string} returns.type - The parsed type component
16
* @returns {string} returns.subtype - The parsed subtype component
17
* @returns {Map<string, string>} returns.parameters - Map of parameter name-value pairs
18
*/
19
function parse(input);
20
```
21
22
**Import:**
23
24
```javascript
25
const parse = require("whatwg-mimetype/lib/parser");
26
```
27
28
**Usage Examples:**
29
30
```javascript
31
const parse = require("whatwg-mimetype/lib/parser");
32
33
// Successful parsing
34
const result = parse("text/html;charset=utf-8");
35
console.log(result);
36
// {
37
// type: "text",
38
// subtype: "html",
39
// parameters: Map { "charset" => "utf-8" }
40
// }
41
42
// Access parsed components
43
console.log(result.type); // "text"
44
console.log(result.subtype); // "html"
45
console.log(result.parameters.get("charset")); // "utf-8"
46
47
// Failed parsing returns null
48
const invalid = parse("invalid mime type");
49
console.log(invalid); // null
50
51
// Complex parameter parsing
52
const complex = parse('application/json; charset="utf-8"; boundary=something');
53
console.log(complex.parameters.size); // 2
54
console.log(complex.parameters.get("charset")); // "utf-8"
55
console.log(complex.parameters.get("boundary")); // "something"
56
```
57
58
### Serialize Function
59
60
Raw serialization function that converts MIME type record objects back to strings.
61
62
```javascript { .api }
63
/**
64
* Serializes a MIME type record object to a string
65
* @param {Object} mimeType - MIME type record object to serialize
66
* @param {string} mimeType.type - The type component
67
* @param {string} mimeType.subtype - The subtype component
68
* @param {Map<string, string>} mimeType.parameters - Parameter name-value pairs
69
* @returns {string} Serialized MIME type string
70
*/
71
function serialize(mimeType);
72
```
73
74
**Import:**
75
76
```javascript
77
const serialize = require("whatwg-mimetype/lib/serializer");
78
```
79
80
**Usage Examples:**
81
82
```javascript
83
const serialize = require("whatwg-mimetype/lib/serializer");
84
85
// Serialize a MIME type record
86
const mimeType = {
87
type: "text",
88
subtype: "html",
89
parameters: new Map([
90
["charset", "utf-8"],
91
["boundary", "something"]
92
])
93
};
94
95
const serialized = serialize(mimeType);
96
console.log(serialized); // "text/html;charset=utf-8;boundary=something"
97
98
// Serialize with no parameters
99
const simple = {
100
type: "application",
101
subtype: "json",
102
parameters: new Map()
103
};
104
105
console.log(serialize(simple)); // "application/json"
106
107
// Parameters with special characters are quoted automatically
108
const special = {
109
type: "multipart",
110
subtype: "form-data",
111
parameters: new Map([
112
["boundary", "----boundary with spaces----"]
113
])
114
};
115
116
console.log(serialize(special));
117
// 'multipart/form-data;boundary="----boundary with spaces----"'
118
```
119
120
### Combined Usage
121
122
The parse and serialize functions work together to provide low-level MIME type manipulation:
123
124
```javascript
125
const parse = require("whatwg-mimetype/lib/parser");
126
const serialize = require("whatwg-mimetype/lib/serializer");
127
128
// Parse, modify, and serialize
129
const original = "text/html;charset=iso-8859-1";
130
const parsed = parse(original);
131
132
if (parsed) {
133
// Modify the parsed object
134
parsed.parameters.set("charset", "utf-8");
135
parsed.parameters.set("lang", "en");
136
137
// Serialize back to string
138
const modified = serialize(parsed);
139
console.log(modified); // "text/html;charset=utf-8;lang=en"
140
}
141
142
// Round-trip compatibility
143
const input = "APPLICATION/XML; charset=UTF-8";
144
const roundTrip = serialize(parse(input));
145
console.log(roundTrip); // "application/xml;charset=UTF-8"
146
// Note: type/subtype normalized to lowercase, parameter values preserved
147
```
148
149
### Working with MIMEType Class
150
151
The serialize function can also work with MIMEType class instances since they have the same interface:
152
153
```javascript
154
const MIMEType = require("whatwg-mimetype");
155
const serialize = require("whatwg-mimetype/lib/serializer");
156
157
const mimeType = new MIMEType("text/html;charset=utf-8");
158
159
// serialize() works with both raw objects and MIMEType instances
160
const serialized = serialize(mimeType);
161
console.log(serialized); // "text/html;charset=utf-8"
162
163
// This is equivalent to calling toString() on the MIMEType instance
164
console.log(mimeType.toString()); // "text/html;charset=utf-8"
165
console.log(serialized === mimeType.toString()); // true
166
```
167
168
## Use Cases for Raw APIs
169
170
### Custom MIME Type Processing
171
172
```javascript
173
const parse = require("whatwg-mimetype/lib/parser");
174
const serialize = require("whatwg-mimetype/lib/serializer");
175
176
function processContentType(contentTypeHeader) {
177
const parsed = parse(contentTypeHeader);
178
179
if (!parsed) {
180
return null; // Invalid MIME type
181
}
182
183
// Normalize charset parameter
184
if (parsed.parameters.has("charset")) {
185
const charset = parsed.parameters.get("charset").toLowerCase();
186
parsed.parameters.set("charset", charset);
187
}
188
189
// Add default charset for text types
190
if (parsed.type === "text" && !parsed.parameters.has("charset")) {
191
parsed.parameters.set("charset", "utf-8");
192
}
193
194
return serialize(parsed);
195
}
196
197
console.log(processContentType("text/html")); // "text/html;charset=utf-8"
198
console.log(processContentType("text/plain;charset=ISO-8859-1")); // "text/plain;charset=iso-8859-1"
199
```
200
201
### Bulk Processing
202
203
```javascript
204
const parse = require("whatwg-mimetype/lib/parser");
205
206
function analyzeContentTypes(mimeTypeStrings) {
207
const results = {
208
valid: 0,
209
invalid: 0,
210
types: new Map()
211
};
212
213
for (const mimeTypeString of mimeTypeStrings) {
214
const parsed = parse(mimeTypeString);
215
216
if (parsed) {
217
results.valid++;
218
const count = results.types.get(parsed.type) || 0;
219
results.types.set(parsed.type, count + 1);
220
} else {
221
results.invalid++;
222
}
223
}
224
225
return results;
226
}
227
228
const analysis = analyzeContentTypes([
229
"text/html",
230
"application/json",
231
"invalid-mime-type",
232
"image/png",
233
"text/plain"
234
]);
235
236
console.log(analysis);
237
// {
238
// valid: 4,
239
// invalid: 1,
240
// types: Map { "text" => 2, "application" => 1, "image" => 1 }
241
// }
242
```
243
244
## Performance Considerations
245
246
The raw APIs provide optimal performance for scenarios requiring:
247
248
- Bulk processing of MIME type strings
249
- Custom validation logic
250
- Memory-efficient parsing without object instantiation
251
- Integration with existing data structures
252
253
```javascript
254
const parse = require("whatwg-mimetype/lib/parser");
255
256
// More efficient than creating MIMEType instances for validation only
257
function isValidMimeType(mimeTypeString) {
258
return parse(mimeTypeString) !== null;
259
}
260
261
// Efficient batch validation
262
function validateMimeTypes(mimeTypeStrings) {
263
return mimeTypeStrings.filter(isValidMimeType);
264
}
265
```