Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // var mimetypes = require('path/to/mimetypes');
- // mimetypes.guess('path/to/file.txt');
- // mimetypes.extension('application/javascript');
- 'use strict';
- const fs = require('fs');
- const path = require('path');
- const MIMETYPE_OCTEAT_STREAM = 'application/octeat-stream';
- class MimeTypes {
- constructor(file) {
- this.types = new Map;
- this.extensions = new Map;
- this.load(file);
- }
- load(file) {
- const content = fs.readFileSync(file, 'ascii');
- const lines = content.split('\n');
- for (let line of lines) {
- // Удаляем комментарий
- line = line.replace(/#.*/, '').trim();
- // Пустая строка
- if (!line) {
- continue;
- }
- const fields = line.split(/\s+/);
- // Не указаны расширения
- if (fields.length < 2) {
- continue;
- }
- const type = fields[0];
- const extensions = fields.slice(1);
- this.extensions.set(type, extensions[0]);
- for (const extension of extensions) {
- this.types.set(extension, type);
- }
- }
- }
- /**
- * Возвращает MIME type для файла.
- * @param {string} file Имя файла.
- * @return {string}
- */
- guess(file) {
- const type = this.types.get(path.extname(file).slice(1));
- if (type) {
- return type;
- }
- return MIMETYPE_OCTEAT_STREAM;
- }
- /**
- * Возвращает расширение файла для определенного типа.
- * @param {string} type MIME-Type.
- * @return {string}
- */
- extension(type) {
- const extension = this.extensions.get(type);
- // Добавляем точку к расширению
- return extension ? '.' + extension : '';
- }
- }
- module.exports = new MimeTypes(path.join(__dirname, 'mime.types'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement