-
-
Notifications
You must be signed in to change notification settings - Fork 312
/
Mime.js
64 lines (55 loc) · 1.85 KB
/
Mime.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* @param typeMap [Object] Map of MIME type -> Array[extensions]
* @param ...
*/
function Mime() {
this._types = Object.create(null);
this._extensions = Object.create(null);
for (var i = 0; i < arguments.length; i++) {
this.define(arguments[i]);
}
}
/**
* Define mimetype -> xtension mappings. Each key is a mime-type that maps
* to an array of extensions associated with the type. The first extension is
* used as the default extension for the type.
*
* e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
*
* @param map (Object) type definitions
*/
Mime.prototype.define = function(typeMap, force) {
for (var type in typeMap) {
var extensions = typeMap[type];
for (var i = 0; i < extensions.length; i++) {
var ext = extensions[i];
if (!force && (ext in this._types)) {
throw new Error('Attempt to change mapping for "' + ext + '" extension from "' + this._types[ext] + '" to "' + type + '". Pass \`force=true\` to allow this, otherwise remove "' + ext + '" from the list of extensions for "${type}".');
}
this._types[ext] = type;
}
// Use first extension as default
if (force || !this._extensions[type]) {
this._extensions[type] = extensions[0];
}
}
}
/**
* Lookup a mime type based on extension
*/
Mime.prototype.getType = function(path) {
path = String(path);
var last = path.replace(/.*[\/\\]/, '').toLowerCase();
var ext = last.replace(/.*\./, '').toLowerCase();
var hasPath = last.length < path.length;
var hasDot = ext.length < last.length - 1;
return (hasDot || !hasPath) && this._types[ext] || null;
}
/**
* Return file extension associated with a mime type
*/
Mime.prototype.getExtension = function(type) {
type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
return type && this._extensions[type.toLowerCase()] || null;
}
module.exports = Mime;