node.js - Intl.NumberFormat 在 Node 和浏览器中的不同行为

标签 node.js icu

如果我在浏览器和 Node 中运行这段代码,我会得到两个不同的结果:

const moneyFormatter = new Intl.NumberFormat('it-IT', {
    style: 'currency',
    currency: 'EUR',
    minimumFractionDigits: 2
});

moneyFormatter.format(1);

浏览器:1,00 €

Node :€1.00

最佳答案

ICU 和 Node

这个问题是由于缺少ICU引起的默认 Node 构建中的数据。

Nodejs docs explain it这个功能很好:

Node.js (and its underlying V8 engine) uses ICU to implement these features in native C/C++ code. However, some of them require a very large ICU data file in order to support all locales of the world.

及其在默认 Node 构建中的局限性:

Because it is expected that most Node.js users will make use of only a small portion of ICU functionality, only a subset of the full ICU data set is provided by Node.js by default.

所以:

Several options are provided for customizing and expanding the ICU data set either when building or running Node.js.

快速解决方案

安装 full-icu npm 包就大功告成了:每个语言环境都将被安装并可以使用。只需使用指向 icu 数据集安装的专用环境变量启动您的应用程序:

NODE_ICU_DATA=node_modules/full-icu node YOURAPP.js

或者,使用替代 Node 选项:

node --icu-data-dir=node_modules/full-icu YOURAPP.js

此解决方案的唯一缺点是完整 icu 数据集所需的空间:~27Mb。

速度慢但空间优化的解决方案

从源代码编译 Node bundling it with only a specific ICU .

检查可用的语言环境

Intl.NumberFormat.supportedLocalesOf('it')

如果不支持语言环境,它返回一个空数组[]。 如果支持语言环境,它会返回一个带有语言环境 ID ['it'] 的数组。

关于node.js - Intl.NumberFormat 在 Node 和浏览器中的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55183776/

相关文章:

node.js - Express.js 和 Neo4j

node.js - 作为守护进程运行的带有 redis 的 Docker 容器不运行

php - 如何创建用于 PHP 的 ICU 资源文件?

iphone - ICU 在 iOS 上的 MessageFormat

icu - 为什么 ICU 在执行 reinterpret_cast 时使用此别名屏障?

javascript - Angular - 路由为什么我的 Controller 被调用两次

mysql - 使用 local.js 存储 sails-mysql 密码

javascript - peerjs webrtc调用响应

python - 如何使用 PyICU 将 unicode 文本转写为 ASCII?

c - 我如何使用 ICU 库打印文件?