Localization in node.js with express

牧云@^-^@ 提交于 2019-12-03 05:48:10

node-localize can work together with express.

Depending on where you want the localization, jqtpl-express-i18n can do the job for templating.

I used localizify library in own project, it's very light.

const localizify = require('localizify');

// ...

app.configure(() => {
    app.use((request, response, next) => {
        const lang = request.headers['accept-language'] || 'en';
        localize.setLocale(lang);
        next();
    });
});

You can use language-translator library. It uses json files to load texts. You can define languages whatever you want.

  • It supports parametrized requests.(that contains :parameter)
  • It supports output text both of route file and view file.
  • It is fully customizable.
  • It uses and manage cookie to know user preference.
  • It loads language file in middleware function by matching your route path and language file. No needs to require language files in every route file.
  • It translates default language's json files' texts by using Yandex translate API. (Free)

Actually I use this NPM Package i18n

It have a very simple usage with Express framework... create locales folder (it.json, en.json, etc...)

// load modules at bootstrap
var app = express();
var i18n = require("i18n");

//set configuration
i18n.configure({
  locales:['en', 'de'],
  directory: __dirname + '/server/locales'
});
app.use(i18n.init);


// and then, in controller we can use response
res__('YOUR_KEY')

Front End side just set the HTTP header Accept-Language with value 'en', 'it', etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!