Warm tip: This article is reproduced from serverfault.com, please click

cron-node.js i18n:“ ReferenceError:__未定义”

(cron - node.js i18n: "ReferenceError: __ is not defined")

发布于 2020-12-01 15:20:26

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

Questioner
Nick
Viewed
0
2,854 2020-12-05 01:55:05

在注释中,询问者澄清了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');
}