Nuxt/examples/with-sockets/server.js

41 lines
995 B
JavaScript
Raw Normal View History

2018-03-16 19:52:17 +00:00
import http from 'http'
2018-03-16 16:12:06 +00:00
import { Nuxt, Builder } from 'nuxt'
import express from 'express'
import SocketIO from 'socket.io'
2017-01-18 16:25:06 +00:00
const port = process.env.PORT || 3000
const isProd = process.env.NODE_ENV === 'production'
2018-03-16 16:12:06 +00:00
const app = express()
const server = http.createServer(app)
const io = SocketIO(server)
2017-01-18 16:25:06 +00:00
// We instantiate Nuxt.js with the options
2018-08-08 10:54:05 +00:00
const config = require('./nuxt.config.js')
2017-01-18 16:25:06 +00:00
config.dev = !isProd
2017-10-20 07:13:17 +00:00
const nuxt = new Nuxt(config)
// Start build process in dev mode
2017-01-18 16:25:06 +00:00
if (config.dev) {
2017-10-20 07:13:17 +00:00
const builder = new Builder(nuxt)
builder.build()
2017-01-18 16:25:06 +00:00
}
2017-10-20 07:13:17 +00:00
app.use(nuxt.render)
2017-01-18 16:25:06 +00:00
// Listen the server
server.listen(port, '0.0.0.0')
2017-01-18 17:04:41 +00:00
console.log('Server listening on localhost:' + port) // eslint-disable-line no-console
2017-01-18 16:25:06 +00:00
// Socket.io
2018-08-08 10:54:05 +00:00
const messages = []
2017-01-18 16:25:06 +00:00
io.on('connection', (socket) => {
socket.on('last-messages', function (fn) {
fn(messages.slice(-50))
2017-10-20 07:13:17 +00:00
})
2017-01-18 16:25:06 +00:00
socket.on('send-message', function (message) {
messages.push(message)
socket.broadcast.emit('new-message', message)
})
2017-10-20 07:13:17 +00:00
})