如何在无服务器节点js中使用i18next?

时间:2018-07-08 08:20:25

标签: node.js internationalization azure-functions serverless

我正在使用Node JS Azure函数。我正在尝试使i18next函数返回的错误消息国际化。我可以找到带有快速或普通节点服务器的示例。在这种情况下,可以使用中间件模式。

但是对于函数,我需要一种方法,它可能使用我找不到的语言参数来调用i18next.t('key')。在每次调用i18next.t('key')之前调用i18next.changeLanguage()似乎不切实际。

我的基本代码如下

const i18next = require("i18next");
const backend = require("i18next-node-fs-backend");

const options = {
    // path where resources get loaded from
    loadPath: '../locales/{{lng}}/{{ns}}.json',
    // path to post missing resources
    addPath: '../locales/{{lng}}/{{ns}}.missing.json',
    // jsonIndent to use when storing json files
    jsonIndent: 4
};

i18next.use(backend).init(options);

exports.getString = (key, lang) => {
   //i18next.changeLanguage(lang,
   return i18next.t(key);
}

是否可以在不进行changeLanguage的情况下获取翻译?

1 个答案:

答案 0 :(得分:1)

正如注释中所指出的,每当需要定义或更改语言时,都需要调用i18next.changeLanguage(lang)函数。

您可以查看documentation here

代码看起来像这样

const i18next = require('i18next')
const backend = require('i18next-node-fs-backend')

const options = {
    // path where resources get loaded from
    loadPath: '../locales/{{lng}}/{{ns}}.json',
    // path to post missing resources
    addPath: '../locales/{{lng}}/{{ns}}.missing.json',
    // jsonIndent to use when storing json files
    jsonIndent: 4
}

i18next.use(backend).init(options)

exports.getString = (key, lang) => {
    return i18next
        .changeLanguage(lang)
        .then((t) => {
            t(key) // -> same as i18next.t
        })
}