The results depend on the ICU data used by Node. From site.icu-project.org:
ICU is a mature, widely used set of – – libraries providing Unicode and Globalization support for software applications. ICU is widely portable and gives applications the same results on all platforms – –.
Node 13+
Starting from version 13.0.0, Node comes with full ICU support by default. This means that formatting numbers should automatically work the same way in Node (from version 13 onwards) as it does in browsers.
From v13 changelog:
Node.js releases are now built with default full-icu support. This means that all locales supported by ICU are now included and Intl-related APIs may return different values than before (Richard Lau) #29887.
Issue #19214 has also relevant discussion about this.
Note: v13 is not an LTS (long-time support) version, but v14 is, so v14 is a better choice. See Node.js Releases.
Node 12 and earlier
You need to install and enable full ICU data manually. Here's how:
Run npm install full-icu --save
.
Run also npm install cross-env --save
to support Windows users (optional but recommended).
Update the scripts
section of package.json
to set the environment variable NODE_ICU_DATA
. For example:
{
"scripts": {
// Before
"start": "react-scripts start",
"test": "react-scripts test",
// After (omit "cross-env" if you didn't install the package in step two)
"start": "react-scripts start",
"test": "cross-env NODE_ICU_DATA=node_modules/full-icu react-scripts test"
}
}
This way, when you run npm test
, Node will load the full ICU data from node_modules/full-icu
, and you should get consistent results between browser and server environments.
You could also modify the start
script, but it might be unnecessary; depends on what the script does. In the example above, the script opens a browser, so modifying it would be unnecessary.
Disclaimer: I haven't tested whether this affects performance. In my case, I did this to fix Jest tests of an app that runs in the browser, so a small performance hit when running the tests would have been acceptable.
For further details, see "Internationalization support" in Node (v12) docs.
Kudos to Rndmax's answer here: Date toLocaleDateString in node