Access to i18n inside Socket.io

486 views Asked by At

I use i18n-2 for Internationalization like this:

    router.get('/route', function (req, res, next) {
      res.redirect('/route/?lang=' + req.i18n.getLocale());
   });

Right now, i want to access req.i18n inside Socket.io block. i use Socket.io like this:

    io.on('connection', function(client){ 
        client.on('event', function(data){
          ...
        });
    });

But here, i don't access req to use i18n. How i can solve this?

1

There are 1 answers

3
Travis Kaufman On BEST ANSWER

If you look at the expressBind method of i18n-2, all it does is attach an i18n property to the request object as well as some method proxies for the response object (to use in templates I would assume). You can do the same thing with your client.

var I18n = require('i18n-2');
io.on('connection', function(client) {
  client.i18n = new I18n(/* options */);
  client.on('event', function(data) {
    // use client.i18n.__
  });
});

You could also get fancier and use util.inherits to give the client the same methods that i18n has, but personally I prefer the first way.