[英]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.