http.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. const http = require('http');
  2. const fs = require('fs');
  3. const path = require('path');
  4. //mod:新增http服务,暂时未用到,代码暂留
  5. class HttpServer {
  6. constructor() {
  7. this.server = null;
  8. }
  9. start() {
  10. const staticDir = path.join(__dirname, '../config'); // 从config文件中读取静态资源目录,默认为public目录
  11. this.server = http.createServer((req, res) => {
  12. let filePath = path.join(staticDir, req.url === '/' ? 'index.html' : req.url);
  13. const extname = String(path.extname(filePath)).toLowerCase();
  14. const mimeTypes = {
  15. '.html': 'text/html',
  16. '.js': 'text/javascript',
  17. '.css': 'text/css',
  18. '.json': 'application/json',
  19. '.png': 'image/png',
  20. '.jpg': 'image/jpg',
  21. '.gif': 'image/gif',
  22. '.wav': 'audio/wav',
  23. '.mp4': 'video/mp4',
  24. '.woff': 'application/font-woff',
  25. '.ttf': 'application/font-ttf',
  26. '.eot': 'application/vnd.ms-fontobject',
  27. '.otf': 'application/font-otf',
  28. '.svg': 'application/image/svg+xml'
  29. };
  30. const contentType = mimeTypes[extname] || 'application/octet-stream';
  31. fs.readFile(filePath, (error, content) => {
  32. if (error) {
  33. if (error.code === 'ENOENT') {
  34. res.writeHead(404);
  35. res.end('404 Not Found');
  36. } else {
  37. res.writeHead(500);
  38. res.end(`Server Error: ${error.code}`);
  39. }
  40. } else {
  41. res.writeHead(200, { 'Content-Type': contentType });
  42. res.end(content, 'utf-8');
  43. }
  44. });
  45. });
  46. const port = 7072; // 从config文件中读取端口号,默认为7072
  47. this.server.listen(port, () => {
  48. console.log(`HTTP Server running at http://localhost:${port}/`);
  49. });
  50. }
  51. stop() {
  52. if (this.server) {
  53. this.server.close(() => {
  54. console.log('HTTP Server closed');
  55. });
  56. }
  57. }
  58. }
  59. module.exports = HttpServer;