AceDevHub
Intermediate Node.js Interview QuestionsIntermediateConcept

Node.js · Question 35

What is the difference between require and import in Node.js?

Direct answer

require is CommonJS — synchronous, can run anywhere, returns a copied exports object; import is ESM — hoisted, async module graph, live bindings for named exports; use dynamic import() from CJS or await import() for conditional loads.

Mixing require in .mjs or top-level import in .cjs throws — file extension and package.json type define which loader runs.

  • require(id) — resolves path, loads synchronously, caches by resolved filename.
  • import decl — must be static string at top level (except dynamic import()).
  • import() — returns Promise; works in CJS and ESM for lazy/conditional loading.
  • Default vs named — require gives module.exports; import default from matches .default interop for CJS.
require-vs-import.mjs
// ESM static import (evaluated before other code in module)
import fs from "node:fs/promises";

// Dynamic import — conditional, async
async function loadPlugin(name) {
  const mod = await import(`./plugins/${name}.js`);
  return mod.default;
}

// From CommonJS file only:
// const fs = require("node:fs");
// (async () => { const m = await import("node:fs/promises"); })();