Internationalization (i18n) is one essential part of any application. This can be achieved easily in Nodejs with the the module i18n. There is another module called i18n-2, which is based on i18n and designed specifically to work out-of-the-box with Express.js. In this post, I will focus mostly on i18n-2.
First, you need to install i18n-2 using npm
After that, add these config line into your
app.js file. Remember to add it
after you have loaded the
The i18n object will now reside within the request object of each request.
The above config also allows the locale to be set from query string or from
cookie. For example, the
mysite.com/?lang=en will automatically set the locale
en. To use the i18n object, simply use the
Or if you want to use it in your view, simply use
i18n-2 will then look up the key hello in the locale files (by default located in locales/en.js and locales/vi.js). If the keys or the files is not exist yet, it will then create those files and keys automatically for you so you don’t have to worry about the errors. You can then open those files and edit the values already there or add your new one. The file syntax is just normal JSON syntax.
Note: you cannot use
// for comments.
To change the language, you can set it directly using
function. Beside that, you can set the cookie
locale value for the browser to
remember the current language for the next access.