erwin erwin - 28 days ago 20
Node.js Question

node.js i18n.__ is not a function

I am trying to use i18n within my test node.js/express4 server api

I installed i18n-2,
and updated my server.js

var express = require('express');
var app = express();
var i18n = require('i18n-2');

i18n.expressBind(app, {
// setup some locales - other locales default to en silently
locales: ['en', 'fr'],
// set the default locale
defaultLocale: 'fr',
// set the cookie name
cookieName: 'locale'
});

// set up the middleware
app.use(function(req, res, next) {
req.i18n.setLocaleFromQuery();
req.i18n.setLocaleFromCookie();
next();
});

console.log(i18n.__('Hello'));


I have added 2 files ./locales/en.js

{
"Hello": "Hello",
}


and ./locales/fr.js

{
"Hello": "Salut",
}


but when I start my server, I get an error on
console.log(i18n.__('Hello'));


What am I doing wrong ?

Answer

Your i18n is just a constructor and you need to instantiate it first. By using expressBind you are getting an instance of i18n in each req.

var express     = require('express');
var app         = express();
var i18n        = require('i18n-2');

i18n.expressBind(app, {
  // setup some locales - other locales default to en silently
  locales: ['en', 'fr'],
  // set the default locale
  defaultLocale: 'fr',
  // set the cookie name
  cookieName: 'locale'
});

// set up the middleware
app.use(function(req, res, next) {
  req.i18n.setLocaleFromQuery();
  req.i18n.setLocaleFromCookie();
  console.log(req.i18n.__("Hello"));
  next();
});

app.listen(3000);

If you want to use i18n outside of requests, you need to manually create an instance with new.

Comments