Nic*_*ick 3 cron internationalization node.js i18n-node
在我的整个应用程序中,我使用起来i18n没有问题。但是,对于通过 cron 作业发送电子邮件,我收到错误:
引用错误:__ 未定义
在app.js我配置 i18n 中:
const i18n = require("i18n");
i18n.configure({
locales: ["en"],
register: global,
directory: path.join(__dirname, "locales"),
defaultLocale: "en",
objectNotation: true,
updateFiles: false,
});
app.use(i18n.init);
Run Code Online (Sandbox Code Playgroud)
在我的应用程序中,我将其用作__('authentication.flashes.not-logged-in'),就像我说的那样,没有任何问题。在由 cron 作业调用的邮件控制器中,我以相同的方式使用它:__('mailers.buttons.upgrade-now')。然而,只有在那里,它才会产生上述错误。
只是为了尝试,我已在邮件控制器中将其更改为i18n.__('authentication.flashes.not-logged-in'). 但后来我收到另一个错误:
(node:11058) UnhandledPromiseRejectionWarning: TypeError: logWarnFn is not a function
at logWarn (/data/web/my_app/node_modules/i18n/i18n.js:1180:5)
Run Code Online (Sandbox Code Playgroud)
知道如何使通过 cron 作业发送的电子邮件正常工作吗?
在评论中,提问者澄清了 cron 作业mailController.executeCrons()直接调用,而不是向应用程序发出 HTTP 请求。因此,i18n全局对象永远不会被定义,因为应用程序设置代码app.js不会运行。
最好的解决方案是使用i18n实例用法。您可以将对象的实例化和配置I18N分离到一个单独的函数中,然后调用它app.js以将其设置为 Express 中间件,并在函数中mailController.executeCrons()调用它以在通过 cronjob 调用时使用它。
代码概要:
i18n.js(新文件)
const i18n = require("i18n");
// factory function for centralizing config;
// either register i18n for global use in handling HTTP requests,
// or register it as `i18nObj` for local CLI use
const configureI18n = (isGlobal) => {
let i18nObj = {};
i18n.configure({
locales: ["en"],
register: isGlobal ? global : i18nObj,
directory: path.join(__dirname, "locales"),
defaultLocale: "en",
objectNotation: true,
updateFiles: false,
});
return [i18n, i18nObj];
};
module.exports = configureI18n;
Run Code Online (Sandbox Code Playgroud)
app.js
const configureI18n = require('./path/to/i18n.js');
const [i18n, _] = configureI18n(true);
app.use(i18n.init);
Run Code Online (Sandbox Code Playgroud)
mailController.js
const configureI18n = require('./path/to/i18n.js');
const [_, i18nObj] = configureI18n(false);
executeCrons() {
i18nObj.__('authentication.flashes.not-logged-in');
}
Run Code Online (Sandbox Code Playgroud)