Trantor Liu
Trantor Liu

Reputation: 9126

Node.js - sharing sockets among modules with require

I'm using socket.io. In app.js I set up it and whenever a connection is established, I add the new socket to sockets array. I want to share sockets among modules such as routes by require(). However, app.js also requires the routes, so it forms a require loop. Here's the code.

// app.js
var route = require('routes/route')
    , sockets = [];

exports.sockets = sockets;

// route.js
var sockets = require('../app').sockets;  // undefined

How can I resolve the loop? Or are there other approaches?

Upvotes: 0

Views: 156

Answers (1)

3on
3on

Reputation: 6339

You could do all your socket.IO work inside the route file

var route = require('routes/route').init(io)

with in routes.js

var io;
exports.init = function(io) {
  io = io    
}

Upvotes: 1

Related Questions