3

我在 Windows 8.1 上的 Node.js 版本是:

$ node -v
v5.3.0

但它似乎不支持语言环境识别和协商。我的意思是ECMAScript Internationalization 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 对和都返回相同的en格式:enru

// 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 支持哪些语言环境以及如何启用所需的语言环境?

4

2 回答 2

3

嗨,

根据https://github.com/andyearnshaw/Intl.js/有一个 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');
}
于 2016-02-01T09:18:16.343 回答
2

可以为 API 的不同子集支持不同的语言环境,因此 ECMA-402 不会公开回答是否“支持”语言环境的 API。相反,它公开了每种特定行为形式的API ,以指示该形式是否支持区域设置。因此,如果您想询问是否支持语言环境,则必须单独查询要使用的每个子集。IntlIntl

要查询Intl.NumberFormat对语言环境的支持,请使用以下Intl.NumberFormat.supportedLocalesOf函数:

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

假设 Node 正确支持这一点,isSupportedForNumberFormatting("ru")将返回false,而isSupportedForNumberFormatting("en")将返回true

如果您换入适当的构造函数名称,Intl.Collator类似的代码应该可以工作。Intl.DateTimeFormat如果您正在使用对区域设置敏感的现有 ECMA-262 函数,例如NumberFormat.prototype.toLocaleStringECMA-402 根据Intl原语重新制定的 ECMA-262 函数,请检查相关Intl构造函数的支持(在这种情况下,Intl.NumberFormat)。

于 2016-10-26T21:43:11.183 回答