Firebase Cloud功能中的本地化错误

leo*_*rdo 3 node.js firebase google-cloud-functions

在Firebase Cloud函数中执行时,以下命令将返回美国格式,而不是本地化格式。但是,它在浏览器中效果很好。

price.toLocaleString("pt-BR", {
  maximumFractionDigits: 2
});
Run Code Online (Sandbox Code Playgroud)

有什么办法可以在Firebase云函数中正常运行toLocaleString()吗?

更新:

let price = 1456.21
let formattedPrice = price.toLocaleString("pt-BR", {maximumFractionDigits: 2});

//Value of formattedPrice expected: 1.456,21 (it works in browsers).
//Value of formattedPrice returned in Firebase Cloud Functions: 1,456.21
Run Code Online (Sandbox Code Playgroud)

可能与Node的默认ICU(--with-intl = small-icu)有关。为了支持国际化,似乎该值应为--with-intl = full-icu。

https://nodejs.org/api/intl.html#intl_options_for_building_node_js

Hug*_*sse 8

?? intl似乎不再有效/支持(最后一个版本是 4yo ...)。

我已经实现添加真正的国际如下:

  1. 添加full-icu对 Firebase Cloud Functions 的依赖项: npm install full-icu --save
  2. console.cloud.google.com编辑您的功能(成功部署后)(不要忘记选择正确的 google dev 项目)
  3. 添加NODE_ICU_DATA带有值的环境变量node_modules/full-icu
  4. 保存并等待 1 或 2 分钟以部署功能。

进一步的更新不会删除这个环境,我能够成功地使用 Luxon 的 Intl apis。


Dou*_*son 5

您不应依赖特殊标志来构建Cloud Functions中使用的节点版本。相反,您可以做的是引入处理格式化语言环境字符串的模块。例如,您可以使用intl模块:

npm install intl
Run Code Online (Sandbox Code Playgroud)

使用这个:

const intl = require('intl')
const format = intl.NumberFormat("pt-BR", {maximumFractionDigits: 2})
console.log(format.format(price))
Run Code Online (Sandbox Code Playgroud)