1 var path = require('path');
2 var fs = require('fs');
5 // Map of extension -> mime type
6 this.types = Object.create(null);
8 // Map of mime type -> extension
9 this.extensions = Object.create(null);
13 * Define mimetype -> extension mappings. Each key is a mime-type that maps
14 * to an array of extensions associated with the type. The first extension is
15 * used as the default extension for the type.
17 * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
19 * @param map (Object) type definitions
21 Mime.prototype.define = function (map) {
22 for (var type in map) {
25 for (var i = 0; i < exts.length; i++) {
26 this.types[exts[i]] = type;
29 // Default extension is the first one we encounter
30 if (!this.extensions[type]) {
31 this.extensions[type] = exts[0];
37 * Load an Apache2-style ".types" file
39 * This may be called multiple times (it's expected). Where files declare
40 * overlapping types/extensions, the last file wins.
42 * @param file (String) path of file to load.
44 Mime.prototype.load = function(file) {
45 // Read file and split into lines
47 content = fs.readFileSync(file, 'ascii'),
48 lines = content.split(/[\r\n]+/);
50 lines.forEach(function(line) {
51 // Clean up whitespace/comments, and split into fields
52 var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/);
53 map[fields.shift()] = fields;
60 * Lookup a mime type based on extension
62 Mime.prototype.lookup = function(path, fallback) {
63 var ext = path.replace(/.*[\.\/]/, '').toLowerCase();
65 return this.types[ext] || fallback || this.default_type;
69 * Return file extension associated with a mime type
71 Mime.prototype.extension = function(mimeType) {
72 return this.extensions[mimeType];
76 var mime = new Mime();
79 // http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
80 mime.load(path.join(__dirname, 'types/mime.types'));
82 // Load additional types from node.js community
83 mime.load(path.join(__dirname, 'types/node.types'));
86 mime.default_type = mime.lookup('bin');
89 // Additional API specific to the default instance
95 * Lookup a charset based on mime type.
98 lookup: function(mimeType, fallback) {
99 // Assume text types are utf8
100 return (/^text\//).test(mimeType) ? 'UTF-8' : fallback;
104 module.exports = mime;