https.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const https = require('https')
  2. const fs = require('fs')
  3. const url = require('url')
  4. const path = require('path')
  5. const PORT = 9091
  6. const options = {
  7. key: fs.readFileSync('./privatekey.pem'),
  8. cert: fs.readFileSync('./certificate.pem')
  9. }
  10. const httpsServer = https.createServer(options)
  11. const mime = {
  12. map: {
  13. 'html': 'text/html',
  14. 'xhtml': 'application/xhtml+xml',
  15. 'xml': 'text/xml',
  16. 'js': 'application/javascript',
  17. 'wasm': 'application/wasm',
  18. 'map': 'magnus-internal/imagemap',
  19. 'css': 'text/css',
  20. 'png': 'image/png',
  21. 'jpg': 'image/jpeg',
  22. 'jpeg': 'image/jpeg',
  23. 'gif': 'image/gif',
  24. 'ico': 'image/vnd.microsoft.icon'
  25. },
  26. getType: function (ext) {
  27. let conType = this.map[ext]
  28. return conType || 'text/plain'
  29. }
  30. }
  31. httpsServer.on('request', (req, res) => {
  32. console.log(`[receive request] ${req.method} ${req.url}`)
  33. const urlJson = url.parse(req.url)
  34. let { pathname } = urlJson
  35. if (pathname === '/') pathname += 'index.html'
  36. let ext = pathname.split('.').pop()
  37. res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp')
  38. res.setHeader('Cross-Origin-Opener-Policy', 'same-origin')
  39. let contentType = mime.getType(ext)
  40. res.setHeader('Content-Type', contentType)
  41. fs.readFile(path.resolve(__dirname, pathname.substr(1)), (err, data) => {
  42. if (err) {
  43. res.writeHead(404)
  44. res.end('Not found.')
  45. } else {
  46. res.writeHead(200)
  47. res.end(data)
  48. }
  49. })
  50. })
  51. .listen(PORT)
  52. console.log(`Https server running at https://localhost:${PORT}`)