index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. }
  33. // default text/* to utf-8
  34. if (/^text\//.test(type)) return 'UTF-8'
  35. return false
  36. }
  37. // backwards compatibility
  38. exports.charsets = {
  39. lookup: exports.charset
  40. }
  41. exports.contentType = function (type) {
  42. if (!type || typeof type !== "string") return false
  43. if (!~type.indexOf('/')) type = exports.lookup(type)
  44. if (!type) return false
  45. if (!~type.indexOf('charset')) {
  46. var charset = exports.charset(type)
  47. if (charset) type += '; charset=' + charset.toLowerCase()
  48. }
  49. return type
  50. }
  51. define(exports.json.mime)
  52. define(exports.json.node)
  53. define(exports.json.custom)
  54. function define(json) {
  55. Object.keys(json).forEach(function (type) {
  56. var exts = json[type] || []
  57. exports.extensions[type] = exports.extensions[type] || []
  58. exts.forEach(function (ext) {
  59. if (!~exports.extensions[type].indexOf(ext)) exports.extensions[type].push(ext)
  60. exports.types[ext] = type
  61. })
  62. })
  63. }