Because app.js is usually the main initialization module in your project, it will normally both initialise the web server and socket.io, as well as load other components that the app requires.
As a result, giving io to other modules in the function Object() { [native code] } function of that module is a common approach to distribute it. This is how it would work:
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// load consumer.js and pass it the socket.io object
require('./consumer.js')(io);
// other app.js code follows
Then, in consumer.js:
// define constructor function that gets `io` send to it
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 you want to use a .start() method to initialize things, you can do the same thing with that (minor differences):
// app.js
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// load consumer.js and pass it the socket.io object
var consumer = require('./consumer.js');
consumer.start(io);
// other app.js code follows
And the start method in consumer.js
// consumer.js
// define start method that gets `io` send to it
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);
});
});
};
}
The "push" module of resource sharing is what it's called. By passing it in the function Object() { [native code] }, the module that is loading you pushes some shared information to you.
There are also "pull" models, in which a module calls a method in another module to get the shared information (in this case the io object).
Often, either model can be made to work, but depending on how modules are loaded, who has the needed information, and how modules will be reused in other situations, one or the other will feel more natural.
To know more about Node JS, It's recommended to join Node JS Certification Course today.