Socket.io从快速控制器

时间:2017-10-13 08:21:30

标签: node.js express socket.io controllers emit

我需要从控制器从服务器发出套接字,但我对如何传递io实例感到困惑。 这是我的代码示例,向您展示我的项目结构:

server.js

'use strict'

const mongoose = require('mongoose')
const app = require('./app')
const server = require('http').Server(app)
const io = require('socket.io')(server)
const config = require('./config')

mongoose.connect(config.db, {useMongoClient: true}, (err, res) => {
  if (err) return console.log(`Error: ${err}`)
  console.log('Success')
})

io.on('connection', (socket) => {
  console.log(`Socket id: ${socket.id}`)

  socket.emit('welcome', { message: 'Welcome to API REST' }
})

server.listen(config.port, () => {
  console.log(`Running on port ${config.port}`)
})

app.js

'use strict'

const express = require('express')
const bodyParser = require('body-parser')
const path = require('path')
const hbs = require('express-handlebars')
const app = express()
const api = require('./routes/api')
const web = require('./routes/web')

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.engine('.hbs', hbs({
  defaultLayout: 'default',
  extname: '.hbs'
}))
app.set('view engine', '.hbs')

app.use(express.static('public'))
app.use('/scripts', express.static(path.join(__dirname, 
'/node_modules/')))

app.use('/api', api)
app.use('/', web)

module.exports = app

路由/ api.js

'use strict'

const express = require('express')
const userController = require('../controllers/user')
const api = express.Router()

api.get('/users', userController.getUsers)

module.exports = api

控制器/ user.js的

'use strict'

const User = require('../models/user')

function getUsers (req, res) {
   User.find({}, '-__v -password', (err, users) => {
    if (err) return res.status(500).send({ message: err.message, code: 
 err.code })

    res.status(200).send(users)
  })
}

例如,我需要在controllers / user.js中使用io实例

对此最好的解决方案是什么?

谢谢!

0 个答案:

没有答案