在res范围之外的node.js中使用i18n-2

时间:2019-04-03 19:08:48

标签: javascript node.js internationalization global

我试图瞄准,以便我可以在所调用的函数中使用i18n。

我有错误:

(node:15696) UnhandledPromiseRejectionWarning: TypeError: i18n.__ is not a function

我怎样才能使i18n可以在函数内部工作并且不必在要求之内?

Server.js:

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

global.i18n = i18n;
i18n.expressBind(app, {
    // setup some locales - other locales default to en silently
    locales: ['en', 'no'],
    // change the cookie name from 'lang' to 'locale'
    cookieName: 'locale'
});

app.use(function(req, res, next) {
    req.i18n.setLocaleFromCookie();
    next();
});

//CALL another file with some something here.

otherfile.js:

somefunction() {
               message = i18n.__("no_user_to_select") + "???";

}

我该如何解决?

1 个答案:

答案 0 :(得分:4)

如果您仔细阅读Using with Express.js下的文档,则清楚地记录了它的用法。通过i18n绑定i18n.expressBind到Express应用后,i18n通过req对象可用,该对象可用于所有快递中间件,例如:

req.i18n.__("My Site Title")

因此somefunction应该是像这样的中间件:

function somefunction(req, res, next) {
  // notice how its invoked through the req object
  const message = req.i18n.__("no_user_to_select") + "???";
  // outputs -> no_user_to_select???
}

或者您需要通过类似以下的中间件显式传递req对象:

function somefunction(req) {
  const message = req.i18n.__("no_user_to_select") + "???";
  // outputs -> no_user_to_select???
}

app.use((req, res, next) => {
  somefunction(req);
});

如果您想直接使用i18n,则需要instantiate,如文档所述

const I18n = require('i18n-2');

// make an instance with options
var i18n = new I18n({
    // setup some locales - other locales default to the first locale
    locales: ['en', 'de']
});

// set it to global as in your question
// but many advise not to use global
global.i18n = i18n;

// use anywhere
somefunction() {
  const message = i18n.__("no_user_to_select") + "???";
  // outputs -> no_user_to_select???
}

许多建议不要使用global。

// international.js
// you can also export and import
const I18n = require('i18n-2');

// make an instance with options
var i18n = new I18n({
    // setup some locales - other locales default to the first locale
    locales: ['en', 'de']
});

module.exports = i18n;

// import wherever necessary
const { i18n } = require('./international');