javascript - How can i export socket.io into other modules in nodejs? -


i have socket.io working in app.js when trying call other modules not creating io.connection not sure ?

app.js

var express = require('express'); var app = express(); var server = require('http').createserver(app); var io = require('socket.io')(server); var ditconsumer = require('./app/consumers/ditconsumer'); ditconsumer.start(io); server.listen(3000, function () {     console.log('example app listening on port 3000!'); }); 

consumer.js

module.exports = {     start: function (io) {         consumer.on('message', function (message) {             logger.log('info', message.value);             io.on('connection', function (socket) {                 socket.on('message', function(message) {                     socket.emit('ditconsumer',message.value);                     console.log('from console',message.value);                 });             });         }); } } 

since app.js kind of main initialization module in app, typically both initialize web server , socket.io , load other things needed app.

as such typical way share io other modules passing them other modules in module's constructor function. work this:

var server = require('http').createserver(app); var io = require('socket.io')(server);  // load consumer.js , pass socket.io object require('./consumer.js)(io);  // other app.js code follows 

then, in consumer.js:

// define constructor function gets `io` send module.exports = function(io) {     io.on('connection', function(socket) {         socket.on('message', function(message) {             logger.log('info',message.value);             socket.emit('ditconsumer',message.value);             console.log('from console',message.value);         });     }); }; 

or, if want use .start() method initialize things, can same thing (minor differences):

// app.js var server = require('http').createserver(app); var io = require('socket.io')(server);  // load consumer.js , pass socket.io object var consumer = require('./consumer.js); consumer.start(io);  // other app.js code follows 

and start method in consumer.js

// consumer.js // define start method gets `io` send module.exports = {     start: function(io) {         io.on('connection', function(socket) {             socket.on('message', function(message) {                 logger.log('info',message.value);                 socket.emit('ditconsumer',message.value);                 console.log('from console',message.value);             });         });     }; } 

this known "push" module of resource sharing. module loading pushes shared info passing in constructor.

there "pull" models module calls method in other module retrieve shared info (in case io object).

often, either model can made work, 1 or other feel more natural given how modules being loaded , has desired information , how intend modules reused in other circumstances.


Comments