Use global variable for socket.io

While I have been searching for different alternatives to emit or broadcast with socket.io, the solution is quite simple. Use global variable to access it.

For example in my www (or server.js) file.

app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

// socket io
var io = require('socket.io')(server);  

Simple solution would be

global.io = require('socket.io')(server);  

And access from different file that's been loaded with require for example /routes/users.js

var express = require('express');  
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {  
  io.emit('my-page-status', { 'message': 'hello' });
  res.send('respond with a resource');
});

module.exports = router;  

io variable will be simple accessible and able to send from any fire you’re in.

Alternative solution for the paranoids

 / routes
   / users.js
 - uuid.js
 - server.js

NPM install extra requirements

  • node-uuid

Well that's it.

file: uuid.js

// App UUID random generated on each restart
module.exports = require('node-uuid').v1();  

file: server.js

var app = require('app');  
var debug = require('debug')('couchanime-express:server');  
var http = require('http');  
var uuid = require('uuid');

// Initiate as object
global[uuid] = {}


/**
 * Create HTTP server.
 */

var server = http.createServer(app);

// socket io
global[uuid].io = require('socket.io')(server);  

file: /routes/users.js

var express = require('express');  
var router = express.Router();  
var uuid = require('uuid');

/* GET users listing. */
router.get('/', function(req, res, next) {  
  global[uuid].io.emit('my-page-status', { 'message': 'hello with global variable' });
  res.send('respond with a resource');
});

module.exports = router;  
comments powered by Disqus