[英]How to see what locales a given Node.js version supports and how to enable missing locales?
Windows 8.1上的My Node.js版本是:
$ node -v
v5.3.0
但它似乎不支持區域設置識別和協商。 我的意思是ECMAScript Internationalization API的支持。 僅支持en
locale。 以下是瀏覽器和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
和ru
返回相同的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支持的語言環境,以及如何啟用所需的語言環境?
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');
}
可以為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.Collator
和Intl.DateTimeFormat
。 如果您正在使用區域設置敏感的現有ECMA-262函數,例如NumberFormat.prototype.toLocaleString
,ECMA-402根據Intl
原語重新制定,請檢查相關Intl
構造函數的支持(在這種情況下, Intl.NumberFormat
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.