app.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. const http = require('http')
  2. const express = require('express')
  3. const morgan = require('morgan')
  4. const bodyParser = require('body-parser')
  5. const WebSocket = require('ws')
  6. const EventEmitter = require('events')
  7. const chalk = require('chalk')
  8. const config = require('../config')
  9. const app = module.exports = express()
  10. app.use(morgan('combined'))
  11. app.use(bodyParser.json())
  12. app.use(express.static('dist'))
  13. app.ws = new EventEmitter()
  14. app.listen = (port = config.port || (app.settings.env === 'production' ? 80 : 3000)) => new Promise((resolve, reject) => {
  15. app.server = http.createServer(app)
  16. app.server.once('error', (err) => {
  17. if (err.message.includes('EADDRINUSE') && app.settings.env === 'development' && port < 3999) {
  18. console.warn(err.message)
  19. resolve(app.listen(port + 1))
  20. } else {
  21. reject(err)
  22. }
  23. })
  24. app.server.listen(port, () => {
  25. app.wss = new WebSocket.Server({ server: app.server })
  26. app.wss.on('connection', (...args) => app.ws.emit('connection', ...args))
  27. app.wss.on('message', (...args) => app.ws.emit('message', ...args))
  28. app.wss.on('close', (...args) => app.ws.emit('close', ...args))
  29. app.wss.on('error', (...args) => app.ws.emit('error', ...args))
  30. app.server.port = app.server.address().port
  31. console.log(`Server running at ${chalk.underline(chalk.blueBright(`http://localhost:${app.server.port}`))}`)
  32. resolve()
  33. })
  34. })
  35. module.exports = app