0
# Custom MIME Instances
1
2
Create and configure custom MIME instances with your own type definitions, perfect for specialized applications, custom file types, or when you need mutable MIME type mappings.
3
4
## Capabilities
5
6
### Mime Class Constructor
7
8
Creates a new mutable MIME instance with optional initial type definitions.
9
10
```typescript { .api }
11
/**
12
* Create a new custom mime instance
13
* @param args - Optional TypeMap objects to define initial mappings
14
*/
15
class Mime {
16
constructor(...args: TypeMap[]);
17
}
18
19
type TypeMap = { [key: string]: string[] };
20
```
21
22
**Usage Examples:**
23
24
```typescript
25
import { Mime } from "mime";
26
27
// Empty instance (no initial types)
28
const customMime = new Mime();
29
30
// Instance with predefined types from mime databases
31
import standardTypes from "mime/types/standard.js";
32
import otherTypes from "mime/types/other.js";
33
34
const fullMime = new Mime(standardTypes, otherTypes);
35
36
// Instance with custom types only
37
const appMime = new Mime({
38
"application/x-custom": ["custom", "cust"],
39
"text/x-special": ["special"]
40
});
41
42
// Combining standard and custom types
43
const hybridMime = new Mime(standardTypes, {
44
"application/x-myapp": ["myapp", "ma"]
45
});
46
```
47
48
### Define Custom Type Mappings
49
50
Add or modify MIME type to extension mappings on custom instances.
51
52
```typescript { .api }
53
/**
54
* Define mimetype -> extension mappings
55
* @param typeMap - Object mapping MIME types to extension arrays
56
* @param force - Override existing mappings if true (default: false)
57
* @returns The Mime instance for chaining
58
*/
59
define(typeMap: TypeMap, force?: boolean): this;
60
```
61
62
**Usage Examples:**
63
64
```typescript
65
import { Mime } from "mime";
66
67
const customMime = new Mime();
68
69
// Define new type mappings
70
customMime.define({
71
"application/x-config": ["config", "cfg"],
72
"text/x-log": ["log", "logfile"]
73
});
74
75
// Test the custom mappings
76
customMime.getType("app.config"); // "application/x-config"
77
customMime.getExtension("text/x-log"); // "log"
78
79
// Chain multiple definitions
80
customMime
81
.define({ "application/x-data": ["data"] })
82
.define({ "text/x-notes": ["notes", "note"] });
83
```
84
85
**Force Override Example:**
86
87
```typescript
88
const customMime = new Mime();
89
90
// Initial definition
91
customMime.define({ "text/x-special": ["special"] });
92
93
// This would throw an error (extension conflict)
94
try {
95
customMime.define({ "application/special": ["special"] });
96
} catch (error) {
97
console.log(error.message);
98
// "application/special -> special" conflicts with "text/x-special -> special".
99
// Pass `force=true` to override this definition.
100
}
101
102
// Force override existing mapping
103
customMime.define({ "application/special": ["special"] }, true);
104
customMime.getType("file.special"); // "application/special" (overridden)
105
```
106
107
### Instance Methods
108
109
Custom instances have the same interface as default instances.
110
111
```typescript { .api }
112
/**
113
* Get mime type associated with an extension or file path
114
*/
115
getType(path: string): string | null;
116
117
/**
118
* Get default file extension associated with a mime type
119
*/
120
getExtension(type: string): string | null;
121
122
/**
123
* Get all file extensions associated with a mime type
124
*/
125
getAllExtensions(type: string): Set<string> | null;
126
```
127
128
## Type Database Imports
129
130
### Standard Types Database
131
132
```typescript
133
import standardTypes from "mime/types/standard.js";
134
135
// Contains official, widely-supported MIME types
136
// Examples: text/html, application/json, image/png, etc.
137
const mime = new Mime(standardTypes);
138
```
139
140
### Other Types Database
141
142
```typescript
143
import otherTypes from "mime/types/other.js";
144
145
// Contains vendor-specific and experimental types
146
// Examples: application/vnd.*, application/x-*, etc.
147
const mime = new Mime(otherTypes);
148
```
149
150
### Combined Database (Full MIME compatibility)
151
152
```typescript
153
import { Mime } from "mime";
154
import standardTypes from "mime/types/standard.js";
155
import otherTypes from "mime/types/other.js";
156
157
// Equivalent to the default mime instance
158
const customMime = new Mime(standardTypes, otherTypes);
159
```
160
161
## TypeMap Format
162
163
### Basic TypeMap Structure
164
165
```typescript
166
type TypeMap = { [key: string]: string[] };
167
168
// Example TypeMap
169
const myTypes: TypeMap = {
170
"application/x-myformat": ["myf", "myformat"],
171
"text/x-config": ["config", "cfg", "conf"],
172
"image/x-custom": ["xcust"]
173
};
174
```
175
176
### Extension Priority
177
178
The first extension in the array becomes the default:
179
180
```typescript
181
const customMime = new Mime();
182
customMime.define({
183
"image/custom": ["primary", "secondary", "alt"]
184
});
185
186
customMime.getExtension("image/custom"); // "primary" (first = default)
187
customMime.getAllExtensions("image/custom"); // Set(3) { "primary", "secondary", "alt" }
188
```
189
190
### Starred Extensions
191
192
Extensions starting with `*` are not eligible to be the default extension:
193
194
```typescript
195
const customMime = new Mime();
196
customMime.define({
197
"application/special": ["*rare", "common", "std"]
198
});
199
200
customMime.getExtension("application/special"); // "common" (first non-starred)
201
customMime.getType("file.rare"); // "application/special" (still maps back)
202
```
203
204
## Default Instance Limitations
205
206
**Important**: The default `mime` instances are immutable and cannot be modified:
207
208
```typescript
209
import mime from "mime";
210
211
// This will throw an error
212
try {
213
mime.define({ "custom/type": ["custom"] });
214
} catch (error) {
215
console.log(error.message);
216
// "define() not allowed for built-in Mime objects.
217
// See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances"
218
}
219
```
220
221
**Solution**: Always create custom instances for modification:
222
223
```typescript
224
import { Mime } from "mime";
225
import standardTypes from "mime/types/standard.js";
226
227
// Create mutable version of default instance
228
const mutableMime = new Mime(standardTypes)
229
.define({ "custom/type": ["custom"] });
230
```
231
232
## Advanced Patterns
233
234
### Application-Specific MIME Types
235
236
```typescript
237
import { Mime } from "mime";
238
239
// Create app-specific MIME instance
240
const appMime = new Mime({
241
"application/x-myapp-config": ["myconfig"],
242
"application/x-myapp-template": ["mytemplate", "tpl"],
243
"application/x-myapp-data": ["mydata", "dat"]
244
});
245
246
// Use in application
247
function processFile(filename: string) {
248
const mimeType = appMime.getType(filename);
249
switch (mimeType) {
250
case "application/x-myapp-config":
251
return processConfig(filename);
252
case "application/x-myapp-template":
253
return processTemplate(filename);
254
default:
255
return processGeneric(filename);
256
}
257
}
258
```
259
260
### Fallback Pattern
261
262
```typescript
263
import mime from "mime";
264
import { Mime } from "mime";
265
266
// Custom instance with fallback to default
267
const customMime = new Mime({
268
"application/x-special": ["special"]
269
});
270
271
function getMimeType(filename: string): string | null {
272
// Try custom types first
273
let type = customMime.getType(filename);
274
if (type) return type;
275
276
// Fallback to default mime database
277
return mime.getType(filename);
278
}
279
```
280
281
## Error Handling
282
283
```typescript
284
const customMime = new Mime();
285
286
// Extension conflicts throw errors unless force=true
287
try {
288
customMime.define({ "text/plain": ["txt"] }); // OK
289
customMime.define({ "text/custom": ["txt"] }); // Throws: extension conflict
290
} catch (error) {
291
console.log("Conflict detected:", error.message);
292
293
// Resolve with force flag
294
customMime.define({ "text/custom": ["txt"] }, true);
295
}
296
297
// Invalid inputs return null (same as default instances)
298
customMime.getType(null); // null
299
customMime.getExtension(""); // null
300
```