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()andmodule.export)ES Modules (ESM) – The modern, standard JS module system. (Uses
importandexport)
When you import a module:
Node resolves the file path or package.
Loads the file’s code (and caches it).
Returns the
exportsobject 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