如何查看给定的Node.js版本支持哪些语言环境,以及如何启用缺失的语言环境?

4

我在Windows 8.1上使用的Node.js版本为:

$ node -v
v5.3.0

但它似乎不支持区域设置的识别和协商。我的意思是支持ECMAScript 国际化 API。只有en本地化受到支持。以下是在浏览器和Node.js中的示例。在浏览器中,区域设置可以被很好地识别:

// en
> Intl.NumberFormat('en', {currency: 'USD', style:"currency"}).format(300)
> "$300.00"

// ru
> Intl.NumberFormat('ru', {currency: 'USD', style:"currency"}).format(300)
> "300,00 $"

但在Node.js中它并不起作用。Node.js对于enru都返回相同的en格式:

// en
> Intl.NumberFormat('en', {currency: 'USD', style:"currency"}).format(300)
'$300.00'

// ru
> Intl.NumberFormat('ru', {currency: 'USD', style:"currency"}).format(300)
'$300.00'

有没有办法查看给定的Node.js支持哪些语言环境,并如何启用所需的语言环境?

https://github.com/nodejs/node/issues/15223 - Lonnie Best
2个回答

3

可以支持不同语言环境用于Intl API的不同子集,因此ECMA-402不会公开回答某个语言环境是否“受支持”的API。相反,它为每种特定的行为形式公开API,以指示该语言环境是否支持“该形式”。因此,如果您想问某个语言环境是否受支持,您将需要分别查询您要使用的每个Intl子集。

要查询一个语言环境是否支持Intl.NumberFormat,请使用Intl.NumberFormat.supportedLocalesOf函数:

function isSupportedForNumberFormatting(locale)
{
  return Intl.NumberFormat.supportedLocalesOf([locale]).length > 0;
}

假设Node正确支持此功能,isSupportedForNumberFormatting("ru")将返回false,而isSupportedForNumberFormatting("en")将返回true。类似的代码应该适用于Intl.CollatorIntl.DateTimeFormat,只需要替换相应的构造函数名称。如果您正在使用现有的ECMA-262函数,这些函数是区域设置敏感的,例如NumberFormat.prototype.toLocaleString,那么ECMA-402会使用Intl基元重新制定这些函数,请检查相关的Intl构造函数是否支持(在这种情况下,是Intl.NumberFormat)。

如果您能够获取支持的语言环境和支持的货币列表,那就太好了。 - Lonnie Best
1
考虑到货币变化的频率很低,并且货币是通过代码进行识别,而代码本身始终是一种可用的备选显示形式,对于相当数量的用户来说具有粗略的可读性,因此当前规范行为“我们将为任何已识别的货币提供某些内容”并不太糟糕。在我看来,我已经在您的链接中添加了这方面的评论。如果有足够的需求,规范可以更改以添加测试机制。但我不记得过去有其他人表达过这种担忧。 - Jeff Walden
1
货币并不是我遇到的唯一问题。时区也是一个例子。你不能仅仅问环境,“你支持哪些时区?”而是必须从环境之外的源获取它们。如果你认为时区变化不大,那就看看这个。规范编写者可以在提供反射接口以从环境中获取事物而不是外部来源方面做得更好。 - Lonnie Best

3

你好,

根据https://github.com/andyearnshaw/Intl.js/的说法,有一个名为

intl-locales-supported

的nodejs模块,可以显示是否支持某个区域设置。

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');
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接