How to Use the Internationalization APIs in Node.js on IBM Bluemix
This post is to help you get started with using the new ECMA 402 Internationalization APIs in Node.js. In an earlier post I showed you how to query the Accept-Language header setting to determine the appropriate language to use in your Node.js APIs on IBM Bluemix. Now that we have the appropriate language and or locale we can use that value to help us properly format numbers, dates and times, and collate words.
This is an important aspect as the formatting of numbers, dates and times, and sort orders vary greatly across the world. For example in the United States we typically format dates in mm/dd/yy order while in France dates are formatted in dd/mm/yy order. By using the Internationalization APIs, dates and times will automatically be correctly formatted without you having to research all the various formats used across the world.
As of release 0.12.0 Node.js includes the Internationalization APIs. With that being said, only the English United States locale is included by default. To enable the Internationalization APIs to work in other languages and locales you need to include the optional locale data. The additional language and locale data comes from the International Components for Unicode project. Fortunately, it is very simple to add the additional locales to either a local instance of Node.js or Node.js running on IBM Bluemix and all you need to do is follow these steps:
{
“name”: “ParseLanguage”,
“version”: “0.0.1”,
“private”: true,
“scripts”: {
“start”: “node ./bin/www”
},
“dependencies”: {
“body-parser”: “~1.13.2”,
“debug”: “~2.2.0”,
“express”: “~4.13.1”,
“request”: “^2.60.0”,
“accept-language”: “~2.0.16”,
“full-icu”: “^1.0.2”
}
}
{
“name”: “ParseLanguage”,
“version”: “0.0.1”,
“private”: true,
“scripts”: {
“start”: “node –icu-data-dir=node_modules/full-icu ./bin/www”
},
“dependencies”: {
“body-parser”: “~1.13.2”,
“debug”: “~2.2.0”,
“express”: “~4.13.1”,
“request”: “^2.60.0”,
“accept-language”: “~2.0.16”,
“full-icu”: “^1.0.2”
}
}
var supportedLanguages = [‘en-US’, ‘fr-FR’, ‘es-ES’, ‘de-DE’];
acceptLanguage.languages(supportedLanguages);
// Get the requested client side language
var requestedLanguage = req.headers[‘accept-language’].toString();
var bestLanguageMatch = acceptLanguage.get(requestedLanguage);
var dateStamp = new Intl.DateTimeFormat(bestLanguageMatch).format(new Date());
I hope this post has shown how easy it is for you to use the ECMA 402 Internationalization APIs in your Node.js project.