How to import JSON in Node.js
Loading JSON data is fundamental in Node.js applications, whether for configuration files, test fixtures, or static data sets.
With 12 years of experience building Node.js applications since 2014 and as the creator of CoreUI, I’ve worked with JSON imports across countless production systems.
The most straightforward approach depends on your module system: use require() for CommonJS or import with assertions for ES Modules.
For dynamic loading or runtime flexibility, use fs.readFile() with JSON.parse() to load JSON files on demand.
How to use ESM modules in Node.js
Node.js traditionally used CommonJS modules with require() and module.exports, but modern JavaScript uses ES modules with import and export syntax.
With over 10 years of experience building Node.js applications and as the creator of CoreUI, I’ve migrated numerous projects from CommonJS to ES modules to leverage modern JavaScript features.
From my expertise, the most straightforward approach is to add "type": "module" to your package.json, which enables ESM by default for all .js files.
This method aligns your Node.js code with browser JavaScript and modern tooling.