Web framework.
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.

static.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. var fs = require("fs");
  2. var pathlib = require("path");
  3. var mimes = {
  4. txt: "text/plain",
  5. css: "text/css",
  6. html: "text/html",
  7. js: "application/javascript",
  8. json: "application/json",
  9. xml: "application/xml",
  10. zip: "application/zip",
  11. pdf: "application/pdf",
  12. gif: "image/gif",
  13. png: "image/png",
  14. jpeg: "image/jpeg",
  15. jpg: "image/jpeg",
  16. svg: "image/svg+xml",
  17. bmp: "image/bmp",
  18. webp: "image/webp",
  19. midi: "audio/midi",
  20. mp3: "audio/mpeg",
  21. ogg: "audio/ogg",
  22. webm: "video/webm",
  23. mkv: "video/mkv",
  24. ogv: "video/ogg",
  25. }
  26. function mimetype(path) {
  27. var unknown = "application/octet-stream";
  28. var ext = pathlib.extname(path);
  29. if (ext)
  30. return mimes[ext.substr(1)] || unknown;
  31. else
  32. return unknown;
  33. }
  34. function sendfile(path, app, pathname, res) {
  35. fs.open(path, "r", (err, fd) => {
  36. if (err) {
  37. app.notice(err);
  38. res.writeHead(404);
  39. res.end(app.template(app.res404, { pathname: pathname }));
  40. return;
  41. }
  42. res.writeHead(200, {
  43. "Content-Type": mimetype(path)
  44. });
  45. var rs = fs.createReadStream(null, { fd: fd });
  46. rs.on("error", err => {
  47. app.warning(err);
  48. });
  49. rs.on("data", d => res.write(d));
  50. rs.on("end", () => res.end());
  51. });
  52. }
  53. module.exports = function(root, before) {
  54. return function(req, res, app) {
  55. var pn = req.urlobj.pathname;
  56. // Send a file
  57. function send(path) {
  58. sendfile(path, app, pn, res);
  59. }
  60. // Prevent leaking information
  61. if (pn.indexOf("../") !== -1 || pn.indexOf("/..") !== -1 || pn === "..") {
  62. res.writeHead(403);
  63. res.end(app.template(app.res403, { pathname: pn }));
  64. return;
  65. }
  66. // Join the web root with the request's path name
  67. var path = pathlib.join(root, pn.replace(before, ""));
  68. fs.stat(path, (err, stat) => {
  69. // If there's an error stat'ing, just error
  70. if (err) {
  71. app.notice(err);
  72. res.writeHead(404);
  73. res.end(app.template(app.res404, { pathname: pn }));
  74. return;
  75. }
  76. // If it's a directory, we want the index.html file
  77. if (stat.isDirectory())
  78. path = pathlib.join(path, "index.html");
  79. // Send the file
  80. send(path);
  81. });
  82. }
  83. }