|
| 1 | +const path = require('node:path'); |
| 2 | +const fs = require('node:fs'); |
| 3 | +const { createServer } = require('node:http'); |
| 4 | +const { createRequestHandler } = require('expo-server/vendor/http'); |
| 5 | + |
| 6 | +const CLIENT_DIR = path.join(__dirname, 'dist', 'client'); |
| 7 | +const handler = createRequestHandler({ |
| 8 | + build: path.join(__dirname, 'dist', 'server'), |
| 9 | +}); |
| 10 | +const port = process.env.PORT || 3000; |
| 11 | + |
| 12 | +const MIME_TYPES = { |
| 13 | + '.html': 'text/html', |
| 14 | + '.js': 'application/javascript', |
| 15 | + '.css': 'text/css', |
| 16 | + '.json': 'application/json', |
| 17 | + '.png': 'image/png', |
| 18 | + '.jpg': 'image/jpeg', |
| 19 | + '.svg': 'image/svg+xml', |
| 20 | + '.ico': 'image/x-icon', |
| 21 | + '.woff': 'font/woff', |
| 22 | + '.woff2': 'font/woff2', |
| 23 | + '.ttf': 'font/ttf', |
| 24 | + '.map': 'application/json', |
| 25 | +}; |
| 26 | + |
| 27 | +function serveStatic(req, res, next) { |
| 28 | + if (req.method !== 'GET' && req.method !== 'HEAD') return next(); |
| 29 | + |
| 30 | + const urlPath = decodeURIComponent(req.url.split('?')[0]); |
| 31 | + const filePath = path.join(CLIENT_DIR, urlPath); |
| 32 | + |
| 33 | + if (!filePath.startsWith(CLIENT_DIR)) return next(); |
| 34 | + |
| 35 | + fs.stat(filePath, (err, stats) => { |
| 36 | + if (err || !stats.isFile()) return next(); |
| 37 | + |
| 38 | + const ext = path.extname(filePath); |
| 39 | + const contentType = MIME_TYPES[ext] || 'application/octet-stream'; |
| 40 | + |
| 41 | + res.setHeader('Content-Type', contentType); |
| 42 | + res.setHeader('Cache-Control', 'public, max-age=31536000, immutable'); |
| 43 | + fs.createReadStream(filePath).pipe(res); |
| 44 | + }); |
| 45 | +} |
| 46 | + |
| 47 | +createServer((req, res) => { |
| 48 | + serveStatic(req, res, () => { |
| 49 | + handler(req, res, (err) => { |
| 50 | + if (err) { |
| 51 | + console.error(err); |
| 52 | + res.statusCode = 500; |
| 53 | + res.end('Internal Server Error'); |
| 54 | + } |
| 55 | + }); |
| 56 | + }); |
| 57 | +}).listen(port, () => { |
| 58 | + console.log(`Server listening on port ${port}`); |
| 59 | +}); |
0 commit comments