Advertisement
stuppid_bot

Node.js mime module

Aug 19th, 2013
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. fs = require('fs');
  2.  
  3. function MimeMap(data) {
  4.     data = data.replace(/#.*\n/g, '');
  5.     var lines = data.split('\n');
  6.     var i = lines.length - 1;
  7.     var extensionMap = {};
  8.     var contentTypeMap = {};
  9.  
  10.     while (i--) {
  11.         var fields = lines[i].split(/\s+/);      
  12.         contentTypeMap[fields[0]] = fields[1];
  13.         var j = fields.length;
  14.  
  15.         while (--j) {
  16.             extensionMap[fields[j]] = fields[0];
  17.         }
  18.     }
  19.  
  20.     this.getContentType = function(path) {
  21.         var parts = path.split(/[\\/]+/);
  22.         var filename = parts[parts.length - 1];
  23.         var matches = filename.match(/\.(.*)$/);
  24.  
  25.         if (matches) {
  26.             var extension = matches[1];
  27.             return extensionMap[extension];
  28.         }
  29.     };
  30.  
  31.     this.getExtension = function(contentType) {
  32.         if (contentType in contentTypeMap) {
  33.             return '.' + contentTypeMap[contentType];
  34.         }
  35.     };
  36. }
  37.  
  38. exports.loads = function(path) {
  39.     var data = fs.readFileSync(path, 'ascii');
  40.     return new MimeMap(data);
  41. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement