node.js - Separating modules in NodeJS for use with a single object -


i have nodejs + expressjs + socket.io server , trying divide different namespaces different modules.

essentially want require socket.io library in server.js, have access io variable modules this:

server.js

var app = require('express')(); var jwt = require('jsonwebtoken'); var server = require('http').server(app); var fs = require('fs'); var io = require('socket.io')(server); var bodyparser = require('body-parser');  var _log = require('./logging/loggly.js').client();  // global ns var sk = {     namespaces:{} };  var migrations = require('./sockets/migrations'); var backups = require('./sockets/backups'); var cloudmanager = require('./sockets/cloudmanager');   sk.namespaces[migrations.ns] = migrations; sk.namespaces[backups.ns] = backups; sk.namespaces[cloudmanager.ns] = cloudmanager;  .... .... 

migrations.js

var exports = module.exports = {};   /////////////////////////////////////////////// // //  migrations namespace // /////////////////////////////////////////////// exports.ns = 'migrations';  exports.socket = io.of('/'+exports.ns); // problem 'io' undefined here  exports.socket.on('connection', function(socket){  }); 

i have same code in 3 of socket.io namespaces, don't have access io variable used in server.js. there way have access here? use require()? whats best way achieve functionality?

thank you

you can export function migrations.js accepts io value parameter:

module.exports = function (io) {   var socket = io.of('/'+exports.ns);   socket.on('connection', function(socket){});   return {     ns: 'migrations',     socket: socket,   }; }; 

then require , invoke function in server.js:

var migrations = require('./sockets/migrations')(io); 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -