The i18n
module is often used for internationalization (i18n) in Node.js applications. It helps you manage and localize your application's content for different languages. Below is a step-by-step guide on how to use the i18n
module in Node.js:
Install the i18n
Module:
You need to install the i18n
module first. Open your terminal and run the following command:
bashnpm install i18n
Set Up Your Project Structure:
Create a folder for your localization files. Typically, you would have a folder structure like this:
project_root ├── locales │ ├── en.json │ ├── fr.json │ └── es.json ├── app.js └── ...
Create Localization Files:
Inside the locales
folder, create JSON files for each supported language. For example, en.json
, fr.json
, es.json
, etc. Each file will contain key-value pairs for the translated strings:
json// en.json
{
"greeting": "Hello!",
"welcome": "Welcome to our app."
}
json// fr.json
{
"greeting": "Bonjour!",
"welcome": "Bienvenue sur notre application."
}
json// es.json
{
"greeting": "¡Hola!",
"welcome": "Bienvenido a nuestra aplicación."
}
Initialize i18n
in Your Application:
In your main application file (e.g., app.js
), require the i18n
module and set it up:
javascriptconst i18n = require('i18n');
i18n.configure({
locales: ['en', 'fr', 'es'],
directory: __dirname + '/locales',
defaultLocale: 'en',
cookie: 'language'
});
// Use the i18n module as middleware
app.use(i18n.init);
This configuration tells i18n
where to find your localization files, what languages are supported, and the default language.
Use Translations in Your Application:
Now you can use the __()
function to get translations in your routes or controllers:
javascriptapp.get('/', (req, res) => {
res.send(__('greeting') + ' ' + __('welcome'));
});
The __()
function is provided by the i18n
module, and it looks up the translation for the specified key based on the current language.
Change Language Dynamically:
You can change the language dynamically based on user preferences or other factors. For example, you can set the language in a route handler:
javascriptapp.get('/change-language/:lang', (req, res) => {
const lang = req.params.lang;
res.cookie('language', lang);
res.redirect('/');
});
In this example, the language is set via a route parameter and stored in a cookie. Adjust this part based on your application's requirements.
That's it! With these steps, you should be able to set up basic internationalization in your Node.js application using the i18n
module. Adjust the configuration and usage based on your specific needs.