Advertisement
stuppid_bot

mimetypes module

Dec 16th, 2016
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // var mimetypes = require('path/to/mimetypes');
  2. // mimetypes.guess('path/to/file.txt');
  3. // mimetypes.extension('application/javascript');
  4. 'use strict';
  5.  
  6. const fs = require('fs');
  7. const path = require('path');
  8.  
  9. const MIMETYPE_OCTEAT_STREAM = 'application/octeat-stream';
  10.  
  11.  
  12. class MimeTypes {
  13.   constructor(file) {
  14.     this.types = new Map;
  15.     this.extensions = new Map;
  16.     this.load(file);
  17.   }
  18.  
  19.   load(file) {
  20.     const content = fs.readFileSync(file, 'ascii');
  21.     const lines = content.split('\n');
  22.     for (let line of lines) {
  23.       // Удаляем комментарий
  24.       line = line.replace(/#.*/, '').trim();
  25.       // Пустая строка
  26.       if (!line) {
  27.         continue;
  28.       }
  29.       const fields = line.split(/\s+/);
  30.       // Не указаны расширения
  31.       if (fields.length < 2) {
  32.         continue;
  33.       }
  34.       const type = fields[0];
  35.       const extensions = fields.slice(1);
  36.       this.extensions.set(type, extensions[0]);
  37.       for (const extension of extensions) {
  38.         this.types.set(extension, type);
  39.       }
  40.     }
  41.   }
  42.  
  43.   /**
  44.    * Возвращает MIME type для файла.
  45.    * @param  {string} file Имя файла.
  46.    * @return {string}
  47.    */
  48.   guess(file) {
  49.     const type = this.types.get(path.extname(file).slice(1));
  50.     if (type) {
  51.       return type;
  52.     }
  53.     return MIMETYPE_OCTEAT_STREAM;
  54.   }
  55.  
  56.   /**
  57.    * Возвращает расширение файла для определенного типа.
  58.    * @param  {string} type MIME-Type.
  59.    * @return {string}
  60.    */
  61.   extension(type) {
  62.     const extension = this.extensions.get(type);
  63.     // Добавляем точку к расширению
  64.     return extension ? '.' + extension : '';
  65.   }
  66. }
  67.  
  68.  
  69. module.exports = new MimeTypes(path.join(__dirname, 'mime.types'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement