-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
36 lines (32 loc) · 1.14 KB
/
server.js
File metadata and controls
36 lines (32 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { createServer } from 'http'
import { readFileSync, existsSync } from 'fs'
import { join, extname } from 'path'
import { fileURLToPath } from 'url'
const __dirname = fileURLToPath(new URL('.', import.meta.url))
const dist = join(__dirname, 'dist')
const port = parseInt(process.env.PORT || '3000')
const basePath = '/apps/hello-react'
const mimeTypes = {
'.html': 'text/html',
'.js': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
}
createServer((req, res) => {
let path = req.url.split('?')[0]
if (path.startsWith(basePath)) path = path.slice(basePath.length)
if (path === '' || path === '/') path = '/index.html'
const filePath = join(dist, path)
if (existsSync(filePath)) {
const ext = extname(filePath)
res.writeHead(200, { 'Content-Type': mimeTypes[ext] || 'application/octet-stream' })
res.end(readFileSync(filePath))
} else {
// SPA fallback
res.writeHead(200, { 'Content-Type': 'text/html' })
res.end(readFileSync(join(dist, 'index.html')))
}
}).listen(port, () => console.log(`Listening on :${port}`))