[英]Initialize i18next in Azure function
我有一个 azure http 触发器函数,它由客户端调用,其中包含一些数据和客户端的文化字符串,例如“en-US”。 index.js 处理 azure 请求。 myWorker.js 有一个函数 doStuff() ,它准备数据返回给客户端。 我正在使用 i18next 进行本地化。
index.js 需要将文化字符串传递给 i18next。 将 i18next 放在 myWorker.js 中似乎合乎逻辑,但它需要在 index.js 调用 doStuff 函数之前加载。 如果这是一团糟,请原谅我,但我是 node 的新手,不知道设置它的最佳方法。
index.js 如何将文化字符串传递给 myworker.js,等待 i18next 加载,将主要数据传递给 dostuff() 并以 context.done() 结束?
index.js
module.exports = async function (context, req) {
switch (req.body.data.action) {
case 'doWork':
let myworker = require('./myWorker')(req.body.data.culture) //culture string for i18next
let retval = myworker.dostuff(); //i18next fails as it isn't loaded yet.
context.res = {
status: 200, body: {someData: retval}
};
break;
case 'anotherCommand':
....
}
context.done();
}
myWorker.js
let i18next = require("i18next");
let backend = require("i18next-node-fs-backend");
function dostuff() {
calc some stuff using i18next.t(key);
}
function setup_i18next(cultr) {
i18next
.use(backend)
.init({
fallbackLng: 'en',
lng: cultr,
backend: {
loadPath: 'locales/{{lng}}/{{ns}}.json'
},
ns: ['myspace1', 'myspace2']
})
.then(function (t) {
????
});
}
module.exports = function(cultre) {
setup_i18next(cultre);
return {
dostuff
}
}
使用 fs-backend,像这样:
// i18n.js
const { join } = require('path')
const { readdirSync, lstatSync } = require('fs')
const i18next = require('i18next')
const Backend = require('i18next-fs-backend')
i18next
.use(Backend)
.init({
// debug: true,
initImmediate: false, // setting initImediate to false, will load the resources synchronously
fallbackLng: 'en',
lng: 'en',
preload: readdirSync(join(__dirname, '../locales')).filter((fileName) => {
const joinedPath = join(join(__dirname, '../locales'), fileName)
const isDirectory = lstatSync(joinedPath).isDirectory()
return isDirectory
}),
ns: 'backend-app',
defaultNS: 'backend-app',
backend: {
loadPath: join(__dirname, '../locales/{{lng}}/{{ns}}.json')
}
})
module.exports = (lng) => i18next.getFixedT(lng || 'en')
然后像这样使用它:
const t = require('../i18n')(lng)
const title = t('invitation.subject')
根据@adrai 的回答(我永远不会想到),我认为可以对其进行调整以在 init.d 中指定语言。 否则,如果通过 lang 指定了另一种语言,我们将不必要地加载“en”翻译。
const { join } = require('path')
const { readdirSync, lstatSync } = require('fs')
const i18next = require('i18next')
const SyncBackend = require('i18next-sync-fs-backend')
module.exports = (lang) => {
i18next
.use(SyncBackend)
.init({
// debug: true,
initImmediate: false,
fallbackLng: 'en',
lng:lang,
preload: readdirSync(join(__dirname, '../locales')).filter((fileName) => {
const joinedPath = join(join(__dirname, '../locales'), fileName)
const isDirectory = lstatSync(joinedPath).isDirectory()
return isDirectory
}),
ns: ['k2locals','sfaDebugger'],
defaultNS: 'k2locals',
debug: true,
backend: {
loadPath: join(__dirname, '../locales/{{lng}}/{{ns}}.json')
}
})
return i18next.getFixedT(lang || 'en', 'k2locals')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.