Well, you can achieve this in many ways, for example:
- setting objects in the global namespace. (changing needs in global needs)
- Use module.exports and claim the object in other files. (can lead to issues with circular addiction if they are not performed properly)
- pass the instance as arguments to the controllers, requiring them in the routes.
myModule.js A module that provides the functionality of your Socket.IO library
const sio = require('socket.io'); module.exports = function(server) { const io = sio(server); return { register: function(namespace) { let nsp = io.of(namespace); nsp.on('connect', function(socket) {
FLOW 1: Install the module in the global namespace.
app.js
var app = require('express').createServer(); var io = require('./myModule')(app); global._io = io; app.listen(80)
controller.js
module.exports = function(io){ var that={}; const _io = global._io; that.myAction = function(req,res){ _io.register('newRoom'); res.send('Done'); } return that; }
Protocol 2: passing the module as arguments.
app.js
var app = require('express').createServer(); var io = require('./myModule')(app); require(./router.js)(app,io); app.listen(80);
router.js
module.exports = function (app,io) {
controller.js
module.exports = function(io){ var that={}; const _io = io; that.myAction = function(req,res){ _io.register('newsRoom'); res.send('Done'); }
Stream 3: Installing io to the global. Thus, you do not need to transfer the server every time.
app.js
var app = require('express').createServer(); require('./myModule')(app); require(./router.js)(app); app.listen(80);
controller.js
// no need to pass the server as io is already initialized const _io = require('./myModule')(); module.exports = function(io){ var that={}; that.myAction = function(req,res){ _io.register('newsRoom'); res.send('Done'); } return that; }
myModule.js
module.exports = function( server ) { const _io = global._io || require('socket.io')(server); if(global._io === undefined){ //initializing io for future use global._io = _io; } return { register: function(namespace) { let nsp = _io.of(namespace); nsp.on('connect', function(socket) { // ... } } } }
Probably the cleanest way is to pass arguments to the controllers, requiring them in routes. Although the third thread seems promising, care must be taken when changing the global namespace.