Artboard 16light, inspiration, solution, idea, innovation,Google Sheets iconSwift icon
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. 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.

Update: Since Node.js 17.5, it's possible to leverage import assertions in ECMAScript modules to import JSON files.

/* 
  Experimental JSON import is supported since Node.js 17.5
  $ 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",
  },
});

But watch out, JSON modules are still marked as experimental in Node.js!

How are things in browser land? Chrome ships import assertions since v91, and if Babel is in your toolchain, you're good to start using it!

This post explains ways to deal with JSON in ES modules if you're using a Node.js version before 17.5 or don't want to use the --experimental-json-modules in Node.js 16.

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 and ESM JSON modules are the way!

For Node.js versions that don't support them yet, I don't know. ๐Ÿคทโ€โ™‚๏ธ Neither option feels good, but I'll probably stick to the first option because it's more understandable.

Related Topics

Related Articles