a.js 984 B

12345678910111213141516171819202122232425262728293031323334
  1. import http from 'http';
  2. import url from 'url';
  3. import path from 'path';
  4. import fs from 'fs';
  5. import os from 'os';
  6. import mime from 'mime';
  7. import { fileURLToPath } from 'url';
  8. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  9. const app = http.createServer((req, res) => {
  10. let rootpath = __dirname;
  11. if (os.platform() === 'darwin' || os.platform() === 'linux')
  12. rootpath = path.join(process.env.HOME, './');
  13. let pathname = url.parse(req.url).pathname;
  14. pathname = pathname == '/' ? '/default.html' : pathname;
  15. let realPath = path.join(__dirname, 'public' + pathname);
  16. let type = mime.getType(realPath);
  17. fs.readFile(realPath, (error, result) => {
  18. if (error != null) {
  19. res.writeHead(404, { 'content-type': 'text/html;charset=utf8' });
  20. res.end('文件读取失败');
  21. } else {
  22. res.writeHead(200, {
  23. 'content-type': type
  24. });
  25. res.end(result);
  26. };
  27. });
  28. });
  29. // 监听 3000 端口
  30. app.listen(3000);
  31. console.log('服务器已启动,监听 3000 端口,请访问 localhost:3000');