Modules

A module in Node.js is just a reusable block of code that has its own context and can export functions, objects, or variables.

Think of a module as a self-contained file that does one thing well and can be imported into other files.

Node.js supports two module systems:

  • CommonJS (CJS) – The original system (used in Node.js since the beginning) (Uses require() and module.export)

  • ES Modules (ESM) – The modern, standard JS module system. (Uses import and export)

When you import a module:

  1. Node resolves the file path or package.

  2. Loads the file’s code (and caches it).

  3. Returns the exports object to the importer.

Caching ensures that if you import/require the same module multiple times, Node doesn’t reload it — it just reuses the cached exports (singleton behavior).

Last updated