Node.js Course
Node.js
/
Intermediate

ES Modules (ESM)

Definition

The official ECMAScript standard for modules, using `import` and `export`. Native to browsers, it is now fully supported in modern Node.js.

Explain Like I'm New

ES Modules are the modern, standardized way to share code. Instead of the old Node-only `require()`, you use the exact same `import` syntax you use in React or Vanilla frontend code. It unifies backend and frontend JavaScript into one standard.

Real World Example

Writing `import { readFile } from 'fs/promises'` in your Node backend, which looks exactly identical to `import { useState } from 'react'` on the frontend.

Common Use Cases

  • •Modern Node.js development
  • •Writing libraries that run in both Node and Browsers

Interactive Example

Loading Code Playground...

Interview Questions

basic

  • How do you tell Node.js to use ES Modules instead of CommonJS?

intermediate

  • Can you use `__dirname` in an ES Module?

advanced

  • What is Top-Level Await?

Flash Cards

Question

How to enable ES Modules in Node?

Click to reveal answer
Answer

You must open your `package.json` and add `"type": "module"`. Alternatively, you can name your specific files with the `.mjs` extension instead of `.js`.

Question

Can you use __dirname?

Click to reveal answer
Answer

No! `__dirname`, `__filename`, and `require` DO NOT exist in ES Modules. You have to reconstruct them using the `import.meta.url` property and the `url` core module.