How to best structure an Express V4.11+ project with Socket.IO? How to best structure an Express V4.11+ project with Socket.IO? express express

How to best structure an Express V4.11+ project with Socket.IO?


A lot of info about socket.io and express are out of date due to their popularity and fast changing pace.

This is what I ended up doing, by no means it's the best.

I would create a sockets.js at the same level as app.js, so you can separate all socket.io initialization logic.

var sockets = {};sockets.init = function (server) {    // socket.io setup    var io = require('socket.io').listen(server);    io.sockets.on('connection', function (socket) {        console.log('socket connected');        // other logic    });}module.exports = sockets;

And in your bin/www file, you can initialize socket.io like this:

#!/usr/bin/env nodevar debug = require('debug')('yourProject');var app = require('../app');var sockets = require('../sockets')app.set('port', process.env.PORT || 3000);var server = app.listen(app.get('port'), function() {    debug('Express server listening on port ' + server.address().port);});sockets.init(server);