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 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. png: "image/png",
  13. jpeg: "image/jpeg",
  14. jpg: "image/jpeg",
  15. gif: "image/gif",
  16. svg: "image/svg",
  17. }
  18. function mimetype(path) {
  19. var unknown = "application/octet-stream";
  20. var ext = pathlib.extname(path);
  21. if (ext)
  22. return mimes[ext.substr(1)] || unknown;
  23. else
  24. return unknown;
  25. }
  26. function sendfile(path, app, pathname, res) {
  27. fs.open(path, "r", (err, fd) => {
  28. if (err) {
  29. app.notice(err);
  30. res.writeHead(404);
  31. res.end(app.template(app.res404, { pathname: pathname }));
  32. return;
  33. }
  34. res.writeHead(200, {
  35. "Content-Type": mimetype(path)
  36. });
  37. var rs = fs.createReadStream(null, { fd: fd });
  38. rs.on("error", err => {
  39. app.warning(err);
  40. });
  41. rs.on("data", d => res.write(d));
  42. rs.on("end", () => res.end());
  43. });
  44. }
  45. module.exports = function(root, before) {
  46. return function(req, res, app) {
  47. var pn = req.urlobj.pathname;
  48. // Send a file
  49. function send(path) {
  50. sendfile(path, app, pn, res);
  51. }
  52. // Prevent leaking information
  53. if (pn.indexOf("../") !== -1 || pn.indexOf("/..") !== -1 || pn === "..") {
  54. res.writeHead(403);
  55. res.end(app.template(app.res403, { pathname: pn }));
  56. return;
  57. }
  58. // Join the web root with the request's path name
  59. var path = pathlib.join(root, pn.replace(before, ""));
  60. fs.stat(path, (err, stat) => {
  61. // If there's an error stat'ing, just error
  62. if (err) {
  63. app.notice(err);
  64. res.writeHead(404);
  65. res.end(app.template(app.res404, { pathname: pn }));
  66. return;
  67. }
  68. // If it's a directory, we want the index.html file
  69. if (stat.isDirectory())
  70. path = pathlib.join(path, "index.html");
  71. // Send the file
  72. send(path);
  73. });
  74. }
  75. }