DEV Community

Stefan Judis
Stefan Judis

Posted on • Originally published at stefanjudis.com

4 1

How to import JSON files in ES modules (Node.js)

ES modules are still reasonably new in Node.js land (they're stable since Node 14). Modules come with a built-in module system and features such as top-level await.

I just read an informative post on ES modules by Pawel Grzybek and learned that you can't import JSON files in ES modules today. That's a real bummer because I'm pretty used to doing const data = require('./some-file.json') in Node.js.

While it will be possible to import JSON from within modules eventually, the implementation is still behind a flag (--experimental-json-modules).

This post includes ways to deal with JSON in ES modules today.

Option 1: Read and parse JSON files yourself

The Node.js documentation advises to use the fs module and do the work of reading the files and parsing it yourself.

import { readFile } from 'fs/promises';
const json = JSON.parse(
  await readFile(
    new URL('./some-file.json', import.meta.url)
  )
);
Enter fullscreen mode Exit fullscreen mode

Option 2: Leverage the CommonJS require function to load JSON files

The documentation also states that you can use createRequire to load JSON files. This is the way Pawel advises in his blog post.

createRequire allows you to construct a CommonJS require function so that you can use typical CommonJS features in Node.js EcmaScript modules.

import { createRequire } from "module";
const require = createRequire(import.meta.url);
const data = require("./data.json");
Enter fullscreen mode Exit fullscreen mode

How should you load JSON files?

I don't know. 🤷‍♂️ Neither option feels good, and I'll probably stick to the first option because it's more understandable.

Let's see when stable JSON modules land in Node.js!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay