Published at
Updated at
Reading time
2min

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 read an informative post on ES modules by Pawel Grzybek and learned that you can't import JSON files in ES modules today.

/* 
  Experimental JSON import in Node.js
  $ node index.mjs
*/

// An import assertion in a static import
import info from `./package.json` assert { type: `json` };

// An import assertion in a dynamic import
const { default: info } = await import("./package.json", {
  assert: {
    type: "json",
  },
});

That's a real bummer because I'm pretty used to doing require calls such as const data = require('./some-file.json') in Node.js.

But can you use import assertions in Node.js today?

At the time of writing, the current Node.js LTS (v18.12) still marks import assertions as experimental.

Before jumping all in with import/assert; apparently, "Import assertions" have been reframed to "Import attributes".

import obj from "mod" with { "type": "json" }

Learn more about it in the new spec proposal.

This post explains ways to deal with JSON in ES modules if you don't want to use the experimental features yet.

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)
  )
);

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 approach is the way Pawel advises in his blog post.

createRequire allows you to construct a CommonJS require function to use typical CommonJS features such as reading JSON in your Node.js EcmaScript modules.

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

How should you load JSON files?

For the future, import assertions are the way to go!

As for the alternatives, neither option feels great, but I'll probably stick to the first option because it's more understandable.

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles