Files
2026-06-29 19:27:33 +08:00

63 lines
1.7 KiB
JavaScript

import { createServer } from 'node:http'
import { readFile } from 'node:fs/promises'
import { extname, join, normalize } from 'node:path'
import { fileURLToPath } from 'node:url'
const root = fileURLToPath(new URL('.', import.meta.url))
const port = Number(process.env.PORT || 4173)
const host = process.env.HOST || '127.0.0.1'
const types = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
}
function resolvePath(url) {
const pathname = decodeURIComponent((url || '/').split('?')[0])
const filePath = normalize(join(root, pathname === '/' ? 'index.html' : pathname))
if (!filePath.startsWith(root)) return null
return filePath
}
const server = createServer(async (request, response) => {
let filePath = resolvePath(request.url)
if (!filePath) {
response.writeHead(403)
response.end('Forbidden')
return
}
try {
const body = await readFile(filePath)
response.writeHead(200, {
'Content-Type': types[extname(filePath)] || 'application/octet-stream',
'Cache-Control': 'no-store',
})
response.end(body)
} catch {
try {
filePath = join(root, 'index.html')
const body = await readFile(filePath)
response.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'no-store',
})
response.end(body)
} catch {
response.writeHead(404)
response.end('Not found')
}
}
})
server.listen(port, host, () => {
console.log(`MLKJ admin app: http://${host}:${port}/`)
})