Im trying to aim so i can use i18n within functions that is called.
I have the error:
(node:15696) UnhandledPromiseRejectionWarning: TypeError: i18n.__ is not a function
How can i make so i18n would work inside functions and dont have to be within a req?
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") + "???";
}
How should i solve this?
If you read the docs carefull under Using with Express.js, it's clearly documented how it's used. After you bind i18n
to express app through i18n.expressBind
, i18n
is available through the req
object available to all express middlewares like:
req.i18n.__("My Site Title")
So somefunction
should either be a middleware like:
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???
}
Or you need to explicitly pass in the req
object through a middleware like:
function somefunction(req) {
const message = req.i18n.__("no_user_to_select") + "???";
// outputs -> no_user_to_select???
}
app.use((req, res, next) => {
somefunction(req);
});
If you want to use i18n
directly you need to instantiate
it as documented like
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???
}
Many discourage use of 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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With