Skip to content

Instantly share code, notes, and snippets.

@crotel
Last active October 16, 2020 09:54
Show Gist options
  • Save crotel/9843b3aece92f6f2a782b709348545bd to your computer and use it in GitHub Desktop.
Save crotel/9843b3aece92f6f2a782b709348545bd to your computer and use it in GitHub Desktop.
class mime sample. add type in need
const mime = {
getType: function (el) {
let t = el.split('.')[1];
this.type = {
json: 'application/json',
ico: 'image/x-icon',
png: 'image/png',
woff: 'font/woff',
woff2: 'font/woff2',
js: 'text/javascript',
css: 'text/css',
html: 'text/html',
};
return this.type[t];
},
};
export { mime };
/*
For using
const mime = require('./mime.js');
or
import { mime } from './mime.js';
mime.getType(filename)
// ex : mime.getType('index.html');
// result : 'text/html'
PS: handle filename if more then one '/' in pathname.
let url = new URL(request.url);
let u = url.pathname;
let t = u.split('.');
filename = t[0].split('/')[(t[0].split('/')).length - 1] + '.' + t[1]; // result as 'index.html'
*/
var path = require('path');
var filePath = '.' + request.url;
var extname = String(path.extname(filePath)).toLowerCase();
var mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.wav': 'audio/wav',
'.mp4': 'video/mp4',
'.m3u8': 'application/vnd.apple.mpegurl',
'.woff': 'application/font-woff',
'.woff2': 'font/woff2',
'.ttf': 'application/font-ttf',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'application/font-otf',
'.wasm': 'application/wasm'
};
var contentType = mimeTypes[extname] || 'application/octet-stream';
/* For using in this case
fs.readFile(filePath, function(error, content) {
if (error) {
if(error.code == 'ENOENT') {
fs.readFile('./404.html', function(error, content) {
response.writeHead(404, { 'Content-Type': 'text/html' });
response.end(content, 'utf-8');
});
}
else {
response.writeHead(500);
response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
}
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment