问题
My Node.js version on Windows 8.1 is:
$ node -v
v5.3.0
But it seems it doesn't support locale identification and negotiation. I mean the support of ECMAScript Internationalization API. Only en
locale is supported. Here is an example in a browser and in Node.js. In a browser a locale is identified just fine:
// en
> Intl.NumberFormat('en', {currency: 'USD', style:"currency"}).format(300)
> "$300.00"
// ru
> Intl.NumberFormat('ru', {currency: 'USD', style:"currency"}).format(300)
> "300,00 $"
But in Node.js it doesn't work. Node.js returns the same en
format for both en
and ru
:
// en
> Intl.NumberFormat('en', {currency: 'USD', style:"currency"}).format(300)
'$300.00'
// ru
> Intl.NumberFormat('ru', {currency: 'USD', style:"currency"}).format(300)
'$300.00'
Is there a way to see what locales does a given Node.js support and how can I enable desired locales?
回答1:
Hy,
According to https://github.com/andyearnshaw/Intl.js/ there is a nodejs module, called
intl-locales-supported
which shows if a locale is supported.
var areIntlLocalesSupported = require('intl-locales-supported');
var localesMyAppSupports = [
/* list locales here */
];
if (global.Intl) {
// Determine if the built-in `Intl` has the locale data we need.
if (!areIntlLocalesSupported(localesMyAppSupports)) {
// `Intl` exists, but it doesn't have the data we need, so load the
// polyfill and patch the constructors we need with the polyfill's.
var IntlPolyfill = require('intl');
Intl.NumberFormat = IntlPolyfill.NumberFormat;
Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat;
}
} else {
// No `Intl`, so use and load the polyfill.
global.Intl = require('intl');
}
回答2:
It's possible to support different locales for different subsets of the Intl
API, so ECMA-402 doesn't expose APIs that answer whether a locale is "supported". Rather, it exposes APIs for each particular form of behavior, to indicate whether a locale is supported for that form. So if you want to ask whether a locale is supported, you'll have to separately query for each Intl
subset you're going to use.
To query Intl.NumberFormat
for support of a locale, use the Intl.NumberFormat.supportedLocalesOf
function:
function isSupportedForNumberFormatting(locale)
{
return Intl.NumberFormat.supportedLocalesOf([locale]).length > 0;
}
Assuming Node properly supports this, isSupportedForNumberFormatting("ru")
would return false
, while isSupportedForNumberFormatting("en")
would return true
.
Similar code should work for Intl.Collator
and Intl.DateTimeFormat
if you swap in the appropriate constructor name. And if you're using existing ECMA-262 functions that are locale-sensitive, like NumberFormat.prototype.toLocaleString
, that ECMA-402 reformulates in terms of Intl
primitives, check for support on the relevant Intl
constructor (in that case, Intl.NumberFormat
).
来源:https://stackoverflow.com/questions/35126247/how-to-see-what-locales-a-given-node-js-version-supports-and-how-to-enable-missi