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

时间:2016-02-01 08:48:22

标签: javascript node.js localization ecmascript-intl

Windows 8.1上的My Node.js版本是:

msg_str = "0105A"; //this gives error. Correct version will be something like "0105AB"
buffer_binary = new Buffer(msg_str, "hex"); // specify hex
console.log(msg_str); 
console.log(buffer_binary);

但它似乎不支持区域设置识别和协商。我的意思是ECMAScript Internationalization API的支持。仅支持$ node -v v5.3.0 区域设置。以下是浏览器和Node.js中的示例。在浏览器中,区域设置被识别为正常:

en

但是在Node.js中它不起作用。 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 $" en返回相同的en格式:

ru

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

2 个答案:

答案 0 :(得分:2)

Hy,

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

的nodejs模块
  

INTL-语言环境支持的

显示是否支持区域设置。

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

答案 1 :(得分:1)

可以为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原语重新制定,请检查相关{{1}的支持构造函数(在这种情况下,Intl)。

相关问题