static-server.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const fs = require("node:fs");
  2. const http = require("node:http");
  3. const path = require("node:path");
  4. const root = process.cwd();
  5. const contentTypes = {
  6. ".css": "text/css; charset=utf-8",
  7. ".html": "text/html; charset=utf-8",
  8. ".js": "text/javascript; charset=utf-8",
  9. ".json": "application/json; charset=utf-8",
  10. ".svg": "image/svg+xml",
  11. ".woff2": "font/woff2"
  12. };
  13. http
  14. .createServer((request, response) => {
  15. response.setHeader("Access-Control-Allow-Origin", "*");
  16. if (request.method === "OPTIONS") {
  17. response.writeHead(204);
  18. response.end();
  19. return;
  20. }
  21. let pathname;
  22. try {
  23. const url = new URL(request.url, "http://127.0.0.1");
  24. pathname = url.pathname === "/" ? "/index.html" : url.pathname;
  25. pathname = decodeURIComponent(pathname);
  26. } catch {
  27. response.writeHead(400);
  28. response.end();
  29. return;
  30. }
  31. const file = path.resolve(root, `.${pathname}`);
  32. if (!file.startsWith(`${root}${path.sep}`)) {
  33. response.writeHead(403);
  34. response.end();
  35. return;
  36. }
  37. fs.readFile(file, (error, content) => {
  38. if (error) {
  39. response.writeHead(error.code === "ENOENT" ? 404 : 500);
  40. response.end();
  41. return;
  42. }
  43. response.writeHead(200, {
  44. "Content-Type": contentTypes[path.extname(file)] || "application/octet-stream"
  45. });
  46. response.end(content);
  47. });
  48. })
  49. .listen(18184, "127.0.0.1");