1

在我的整个应用程序中,我使用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 作业发送的电子邮件正常工作吗?

4

1 回答 1

2

在评论中,提问者澄清说 cron 作业mailController.executeCrons()直接调用,而不是向应用程序发出 HTTP 请求。因此,i18n全局对象永远不会被定义,因为应用程序设置代码app.js没有运行。

最好的解决方案是使用i18n's instance usage。您可以将对象的实例化和配置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');
}
于 2020-12-04T17:18:24.870 回答