Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Object oriented style app with express.js and socket.io

Object oriented style app with express.js and socket.io

Problem

I'm building an application in node, using express for simplify things and socket.io for sockets manipulation.

So, while I'm writing my code I realize that it works, but is not the best and elegant solution.

The only thing I want to do is to wrap all the code of the sockets events, and then reuse in more than one page request, so:

app.js

var express = require('express')
  , io;

var app = express()
  , PORT = 7777;

io = require('socket.io').listen(app.listen(PORT)); 

app.get("/", function ( req, res ) {
  io.socket.on('connection', function ( socket ) { 
    socket.on('user', function () {

    });
    socket.on('message', function () {

    });
    socket.on('getConversation', function ( socket ) {

    });
  });

  res.render('index');
});

But what happens if I want to assign to the /foo and /bar files the same approach?

i.e. I need to get it in a modular or Object Oriented way, as can be possible.

There is a pattern to do it?

Problem courtesy of: Tomi Sebastián Juárez

Solution

All you're doing here is attaching event listeners to socket.io after someone makes a page request. Then every single request after that would be attaching new event listeners and your server slowly begins to run out of memory as you clog it with new event listeners every time someone makes a page request. It makes no sense to put socket.io code in your route handlers. Take a look at this:

https://www.npmjs.com/package/express.io

Solution courtesy of: Chev

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Object oriented style app with express.js and socket.io

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×