WeCodeAcademy

Node.js ES Modules and Top-Level await

Modern Node supports ES modules with import and export (use the .mjs extension or "type": "module" in package.json). They also allow await at the top level. This sample is saved as an .mjs file.

ExampleNode.js
import { readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

const file = join(tmpdir(), "esm-demo.json");
writeFileSync(file, JSON.stringify({ language: "ESM" }));
const data = JSON.parse(readFileSync(file, "utf8"));
console.log(data.language);

const value = await Promise.resolve("top-level await works");
console.log(value);
console.log(typeof require);
Output
ESM
top-level await works
undefined

Inside an ES module require is not defined, which the last line shows. Both module systems exist side by side, so you will meet both.

Quick check

What can ES modules do that CommonJS scripts cannot?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.