在我的整个应用程序中,我使用时都i18n
没有问题。但是,对于通过cron作业发送的电子邮件,出现错误:
ReferenceError:__未定义
在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);
在我的整个应用程序中,我都将其用作__('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)
知道如何使通过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;
app.js
const configureI18n = require('./path/to/i18n.js');
const [i18n, _] = configureI18n(true);
app.use(i18n.init);
mailController.js
const configureI18n = require('./path/to/i18n.js');
const [_, i18nObj] = configureI18n(false);
executeCrons() {
i18nObj.__('authentication.flashes.not-logged-in');
}
我正在尝试解决方案,但是引用app.js会产生错误:
const [i18n, _] = configureI18n(true);
TypeError: configureI18n is not a function or its return value is not iterable
。抱歉,搞乱了导出语法。编辑
i18n.js
使用exports = configureI18n;
,尝试一下。太好了,它有效!谢谢!
不用客气,很高兴我能提供帮助。