Advertisement
stuppid_bot

mimetypes module NodeJS

Dec 16th, 2016
306
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. const fs = require('fs');
  4. const path = require('path');
  5.  
  6. const MIMETYPE_OCTEAT_STREAM = 'application/octeat-stream';
  7.  
  8.  
  9. class MimeTypes {
  10.   constructor(file) {
  11.     this.types = new Map;
  12.     this.extensions = new Map;
  13.     this.load(file);
  14.   }
  15.  
  16.   load(file) {
  17.     // if (!fs.existsSync(file)) {
  18.     //   console.warn(`File does not exists: ${file}`);
  19.     //   return;
  20.     // }
  21.     const data = fs.readFileSync(file, 'ascii');
  22.     const lines = data.split('\n');
  23.     for (let line of lines) {
  24.       line = line.replace(/#.*/, '').trim();
  25.       if (line) {
  26.         const fields = line.split(/\s+/);
  27.         // const type = fields.shift().toLowerCase();
  28.         // const extensions = fields.map(
  29.         //   Function.prototype.call,
  30.         //   String.prototype.toLowerCase
  31.         // );
  32.         // Указан MIME type, но не укзаны расширения
  33.         if (1 > fields.length) {
  34.           continue;
  35.         }
  36.         const type = fields[0];
  37.         const extensions = fields.slice(1);
  38.         this.extensions.set(type, extensions[0]);
  39.         for (const extension of extensions) {
  40.           this.types.set(extension, type);
  41.         }
  42.       }
  43.     }
  44.   }
  45.  
  46.   /**
  47.    * Возвращает MIME type для файла.
  48.    * @param  {string} file Имя файла.
  49.    * @return {string}
  50.    */
  51.   guess(file) {
  52.     // const matches = /\.([^.\/?]+)(?=$|\?)/.exec(url);
  53.     // if (matches) {
  54.     //   const type = this.types.get(matches[1].toLowerCase());
  55.     //   if (type) {
  56.     //     return type;
  57.     //   }
  58.     // }
  59.     const extension = path.extname();
  60.     return MIMETYPE_OCTEAT_STREAM;
  61.   }
  62.  
  63.   /**
  64.    * Возвращает расширение файла для определенного типа.
  65.    * @param  {string} type MIME-Type.
  66.    * @return {string}
  67.    */
  68.   extension(type) {
  69.     // const extension = this.extensions.get(
  70.       // TeXt/HTML ;charset=utf-8 → text/html
  71.     //   type.replace(/^\s*|\s*(?:;.*)?$/g, '').toLowerCase()
  72.     // );
  73.     const extension = this.extensions.get(type);
  74.     // Добавляем точку к расширению
  75.     return extension ? '.' + extension : '';
  76.   }
  77. }
  78.  
  79.  
  80. module.exports = new MimeTypes(path.join(__dirname, 'mime.types'));
  81. // mime = require('D:\\Projects\\NodeReverseProxy\\mimetypes');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement