index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // types[extension] = type
  2. exports.types = Object.create(null)
  3. // extensions[type] = [extensions]
  4. exports.extensions = Object.create(null)
  5. // define more mime types
  6. exports.define = define
  7. // store the json files
  8. exports.json = {
  9. mime: require('./mime.json'),
  10. node: require('./node.json'),
  11. custom: require('./custom.json'),
  12. }
  13. exports.lookup = function (string) {
  14. if (!string || typeof string !== "string") return false
  15. string = string.replace(/.*[\.\/\\]/, '').toLowerCase()
  16. if (!string) return false
  17. return exports.types[string] || false
  18. }
  19. exports.extension = function (type) {
  20. if (!type || typeof type !== "string") return false
  21. type = type.match(/^\s*([^;\s]*)(?:;|\s|$)/)
  22. if (!type) return false
  23. var exts = exports.extensions[type[1].toLowerCase()]
  24. if (!exts || !exts.length) return false
  25. return exts[0]
  26. }
  27. // type has to be an exact mime type
  28. exports.charset = function (type) {
  29. // special cases
  30. switch (type) {
  31. case 'application/json': return 'UTF-8'
  32. case 'application/javascript': return 'UTF-8'
  33. }
  34. // default text/* to utf-8
  35. if (/^text\//.test(type)) return 'UTF-8'
  36. return false
  37. }
  38. // backwards compatibility
  39. exports.charsets = {
  40. lookup: exports.charset
  41. }
  42. exports.contentType = function (type) {
  43. if (!type || typeof type !== "string") return false
  44. if (!~type.indexOf('/')) type = exports.lookup(type)
  45. if (!type) return false
  46. if (!~type.indexOf('charset')) {
  47. var charset = exports.charset(type)
  48. if (charset) type += '; charset=' + charset.toLowerCase()
  49. }
  50. return type
  51. }
  52. define(exports.json.mime)
  53. define(exports.json.node)
  54. define(exports.json.custom)
  55. function define(json) {
  56. Object.keys(json).forEach(function (type) {
  57. var exts = json[type] || []
  58. exports.extensions[type] = exports.extensions[type] || []
  59. exts.forEach(function (ext) {
  60. if (!~exports.extensions[type].indexOf(ext)) exports.extensions[type].push(ext)
  61. exports.types[ext] = type
  62. })
  63. })
  64. }