You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.5 KiB

11 months ago
  1. const MimeLib = require("mime");
  2. class MimeDetector {
  3. nonTextTypes = ["multipart", "model", "audio", "video", "font"];
  4. badMimes = [
  5. "application/octet-stream",
  6. "application/zip",
  7. "application/pkcs8",
  8. "application/vnd.microsoft.portable-executable",
  9. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // XLSX are binaries and need to be handled explicitly.
  10. "application/x-msdownload",
  11. ];
  12. constructor() {
  13. this.lib = MimeLib;
  14. this.setOverrides();
  15. }
  16. setOverrides() {
  17. // the .ts extension maps to video/mp2t because of https://en.wikipedia.org/wiki/MPEG_transport_stream
  18. // which has had this extension far before TS was invented. So need to force re-map this MIME map.
  19. this.lib.define(
  20. {
  21. "text/plain": [
  22. "ts",
  23. "tsx",
  24. "py",
  25. "opts",
  26. "lock",
  27. "jsonl",
  28. "qml",
  29. "sh",
  30. "c",
  31. "cs",
  32. "h",
  33. "js",
  34. "lua",
  35. "pas",
  36. "r",
  37. "go",
  38. "ino",
  39. "hpp",
  40. "linq",
  41. "cs",
  42. ],
  43. },
  44. true
  45. );
  46. }
  47. /**
  48. * Returns the MIME type of the file. If the file has no extension found, it will be processed as a text file.
  49. * @param {string} filepath
  50. * @returns {string}
  51. */
  52. getType(filepath) {
  53. const parsedMime = this.lib.getType(filepath);
  54. if (!!parsedMime) return parsedMime;
  55. return null;
  56. }
  57. }
  58. module.exports = {
  59. MimeDetector,
  60. };