1

I need to emit the socket from the server from controllers, but I'm confuse in how to pass the io instance. Here's a example of my code to show you the structure of my project:

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

routes/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

controllers/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)
  })
}

For example, I need to use the io instance in controllers/user.js

Whats the best solution for this?

Thanks!

  • Did you find a solution for this? – Bolli Dec 02 '17 at 22:41
  • I think I found a solution here: https://stackoverflow.com/questions/10042505/using-socket-io-from-a-module where his server.js is your app.js – Bolli Dec 02 '17 at 23:22
  • For this patternt I used a mix between **socket.io** and Node.js **Events**. Check [this anwser](https://stackoverflow.com/questions/34596689/using-socket-io-in-express-js-project/52103434#52103434). – J.C. Gras Aug 30 '18 at 18:48

1 Answers1

0

Here is the solution for use io as a global variable like this

const app = express();
var http = require("http");
var server=http.createServer(app).listen(2525, (req, res) => {
  console.log("Server running on", 2525);
});
var socketIO = require("socket.io");
var io = socketIO(server);

global.io = io

Add the below statement to your controller code

global.io.emit("eventname", "yourdata");
Noman Malik
  • 1
  • 1
  • 1