|
| 1 | +import http from 'node:http' |
| 2 | +import { Buffer } from 'node:buffer' |
| 3 | +import path from 'node:path' |
| 4 | +import url from 'node:url' |
| 5 | + |
| 6 | +const __dirname = path.dirname(url.fileURLToPath(import.meta.url)) |
| 7 | +const rootDir = path.resolve(__dirname, '..') |
| 8 | +const serverModuleUrl = url.pathToFileURL( |
| 9 | + path.join(rootDir, 'dist/server/server.js'), |
| 10 | +).href |
| 11 | + |
| 12 | +const mod = await import(serverModuleUrl) |
| 13 | +const app = mod.default || mod.app || mod |
| 14 | +const port = Number(process.env.PORT || 3000) |
| 15 | + |
| 16 | +const server = http.createServer(async (req, res) => { |
| 17 | + try { |
| 18 | + const requestUrl = new URL(req.url || '/', `http://localhost:${port}`) |
| 19 | + const chunks = [] |
| 20 | + |
| 21 | + for await (const chunk of req) { |
| 22 | + chunks.push(chunk) |
| 23 | + } |
| 24 | + |
| 25 | + const request = new Request(requestUrl, { |
| 26 | + method: req.method, |
| 27 | + headers: req.headers, |
| 28 | + body: |
| 29 | + req.method === 'GET' || req.method === 'HEAD' |
| 30 | + ? undefined |
| 31 | + : Buffer.concat(chunks), |
| 32 | + }) |
| 33 | + const response = await app.fetch(request) |
| 34 | + |
| 35 | + res.statusCode = response.status |
| 36 | + response.headers.forEach((value, key) => { |
| 37 | + res.setHeader(key, value) |
| 38 | + }) |
| 39 | + |
| 40 | + if (!response.body || req.method === 'HEAD') { |
| 41 | + res.end() |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + res.end(Buffer.from(await response.arrayBuffer())) |
| 46 | + } catch (error) { |
| 47 | + console.error(error) |
| 48 | + res.statusCode = 500 |
| 49 | + res.end(String(error?.stack || error)) |
| 50 | + } |
| 51 | +}) |
| 52 | + |
| 53 | +server.listen(port, () => { |
| 54 | + console.log(`Production server listening on http://localhost:${port}`) |
| 55 | +}) |
0 commit comments