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

mar*_*ria 5 javascript global internationalization node.js

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

我有错误:

(node:15696) UnhandledPromiseRejectionWarning: TypeError: i18n.__ is not a function
Run Code Online (Sandbox Code Playgroud)

我如何才能使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.
Run Code Online (Sandbox Code Playgroud)

otherfile.js:

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

}
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

156*_*223 5

如果您仔细阅读Using with Express.js下的文档,它会清楚地记录它是如何使用的。在您i18n通过绑定到 express app 之后i18n.expressBindi18n可以通过req所有 express 中间件可用的对象使用,例如:

req.i18n.__("My Site Title")
Run Code Online (Sandbox Code Playgroud)

所以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???
}
Run Code Online (Sandbox Code Playgroud)

或者您需要req通过中间件显式传入对象,例如:

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

app.use((req, res, next) => {
  somefunction(req);
});
Run Code Online (Sandbox Code Playgroud)

如果你想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???
}
Run Code Online (Sandbox Code Playgroud)

许多人不鼓励使用 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');
Run Code Online (Sandbox Code Playgroud)