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

// IMPORTANT: This code requires "type": "module" in package.json to run!

// --- file: logger.js ---
// Named export
export const logInfo = (msg) => console.log(`[INFO]: ${msg}`);
// Default export
export default function initLogger() { console.log("Logger ready"); }

// --- file: app.js ---
// Unlike CommonJS, ES Modules usually require the explicit .js extension in Node!
import initLogger, { logInfo } from './logger.js';
import fs from 'fs/promises';

initLogger();
logInfo("App started using ES Modules");

// ES Modules support Top-Level Await! No need to wrap in an async function.
// const data = await fs.readFile('package.json', 'utf-8');
// console.log("File loaded at top level!");

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.