const fs = require('fs') const http = require('http') const path = require('path') const port = Number(process.env.PORT || 8888) const host = process.env.HOST || '127.0.0.1' const root = path.resolve(__dirname, '..', 'dist') const contentTypes = { '.css': 'text/css;charset=utf-8', '.html': 'text/html;charset=utf-8', '.js': 'text/javascript;charset=utf-8', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.svg': 'image/svg+xml', '.ttf': 'font/ttf', '.webp': 'image/webp', '.woff': 'font/woff', '.woff2': 'font/woff2', } function sendFile(file, response) { fs.readFile(file, (error, data) => { if (error) { response.writeHead(404) response.end('Not found') return } response.writeHead(200, { 'Content-Type': contentTypes[path.extname(file)] || 'application/octet-stream', }) response.end(data) }) } http.createServer((request, response) => { const cleanUrl = decodeURIComponent(request.url.split('?')[0]) let file = path.join(root, cleanUrl === '/' ? 'index.html' : cleanUrl) if (!file.startsWith(root)) { response.writeHead(403) response.end('Forbidden') return } fs.stat(file, (error, stats) => { if (error || !stats.isFile()) { file = path.join(root, 'index.html') } sendFile(file, response) }) }).listen(port, host, () => { console.log(`萧康云医 preview http://${host}:${port}/`) })