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.

Global variable

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);
Snippet: bin/www

Simple solution would be

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

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;
Snippet: routes/users.js
io variable will be simple accessible and able to send from any file you’re in.

Alternative solution for the paranoids

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

File Structure

NPM install extra requirements

  • uuid
Well that's it.
// App UUID random generated on each restart
module.exports = require('uuid').v1();
File: uuid.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: server.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;
File: routes/users.js

Alternative Solution: Passing socket.io as argument

Update: 7 Jun 2020