video / server.mjs
Ethscriptions's picture
步骤2:删除旧代码,新建项目骨架(Vite+React+TS、Dockerfile、静态服务器、音频特征、字体子集)
d08438d verified
Raw History Blame Contribute Delete
2.25 kB
// Zero-dependency static server for the built site (supports HTTP Range for audio seeking).
import { createServer } from 'node:http'
import { createReadStream, statSync } from 'node:fs'
import { extname, join, normalize } from 'node:path'
const ROOT = join(process.cwd(), 'dist')
const PORT = Number(process.env.PORT || 3000)
const TYPES = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.woff2': 'font/woff2',
'.mp3': 'audio/mpeg',
'.ico': 'image/x-icon',
}
createServer((req, res) => {
let path = decodeURIComponent((req.url || '/').split('?')[0])
if (path.endsWith('/')) path += 'index.html'
let file = normalize(join(ROOT, path))
if (!file.startsWith(ROOT)) {
res.writeHead(403).end()
return
}
let st
try {
st = statSync(file)
if (st.isDirectory()) {
file = join(file, 'index.html')
st = statSync(file)
}
} catch {
file = join(ROOT, 'index.html')
st = statSync(file)
}
const type = TYPES[extname(file)] || 'application/octet-stream'
const cache = file.includes(`${join(ROOT, 'assets')}`) ? 'public, max-age=31536000, immutable' : 'no-cache'
const range = req.headers.range
if (range) {
const m = /bytes=(\d*)-(\d*)/.exec(range)
const start = m && m[1] ? parseInt(m[1], 10) : 0
const end = m && m[2] ? Math.min(parseInt(m[2], 10), st.size - 1) : st.size - 1
if (start >= st.size || start > end) {
res.writeHead(416, { 'Content-Range': `bytes */${st.size}` }).end()
return
}
res.writeHead(206, {
'Content-Type': type,
'Content-Length': end - start + 1,
'Content-Range': `bytes ${start}-${end}/${st.size}`,
'Accept-Ranges': 'bytes',
'Cache-Control': cache,
})
createReadStream(file, { start, end }).pipe(res)
return
}
res.writeHead(200, { 'Content-Type': type, 'Content-Length': st.size, 'Accept-Ranges': 'bytes', 'Cache-Control': cache })
if (req.method === 'HEAD') res.end()
else createReadStream(file).pipe(res)
}).listen(PORT, '0.0.0.0', () => console.log(`黑街 MV running on http://0.0.0.0:${PORT}`))