server.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/env node
  2. import fs from 'fs'
  3. import path from 'path'
  4. import express from 'express'
  5. import compression from 'compression'
  6. const __dirname = path.dirname(new URL(import.meta.url).pathname)
  7. // JSON files not supported in ESM yet
  8. // https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c#how-can-i-import-json
  9. const vercelJson = JSON.parse(fs.readFileSync(path.join(__dirname, 'vercel.json'), 'utf8'))
  10. const { routes: rawRoutes } = vercelJson
  11. const { PORT = 4002 } = process.env
  12. const app = express()
  13. const exportDir = path.resolve(__dirname, '__sapper__/export')
  14. const routes = rawRoutes.map(({ src, headers, dest }) => ({
  15. regex: new RegExp(src),
  16. headers,
  17. dest
  18. }))
  19. app.use(compression({ threshold: 0 }))
  20. app.use(express.static(exportDir, {
  21. setHeaders (res, thisPath) {
  22. const localPath = '/' + path.relative(exportDir, thisPath)
  23. for (const { regex, headers } of routes) {
  24. if (regex.test(localPath)) {
  25. res.set(headers)
  26. return
  27. }
  28. }
  29. }
  30. }))
  31. routes.forEach(({ regex, headers, dest }) => {
  32. app.get(regex, (req, res) => {
  33. res.set(headers)
  34. res.sendFile(path.resolve(exportDir, dest ? req.path.replace(regex, dest) : req.path))
  35. })
  36. })
  37. app.listen(PORT, () => console.log(`listening on port ${PORT}`))
  38. // Handle SIGINT (source: https://git.io/vhJgF)
  39. process.on('SIGINT', () => process.exit(0))