Sharing variables across files in node.js without using global variables
app.js
var app = express(),
server = require('http').createServer(app),
socket = require('./socket');
var io = require('socket.io').listen(server);
socket(io)
socket.js
module.exports = function (io) {
io.sockets.on('connection', function(socket) {
// Your code here
});
}
One of the ways is by passing the object as argument to function (as already has been described in @Thomas' answer).
Other way is to create a new file say 'global.js'. put only those items in this file that you want to be global. e.g.
var Global = {
io : { }
};
module.exports = Global;
Now, in your app.js,
var app = express(),
server = require('http').createServer(app),
global = require('./global.js');
global.io = require('socket.io').listen(server);
require('./socket');
And in your socket.js:
var global = require('./global.js');
global.io.sockets.on('connection', function(socket) {
//xxx
}
Hope it helps...