Node.js Course
Node.js
/
Beginner

CommonJS Modules

Definition

The original, default module system in Node.js. It uses `require()` to import modules and `module.exports` to export them.

Explain Like I'm New

Imagine every JS file is a locked room. CommonJS is the system for passing notes under the door. You use `module.exports` to shove a note under the door out to the world, and you use `require()` to grab notes from other rooms and pull them inside.

Real World Example

Importing a utility function: `const formatData = require('./utils')`. This is how 90% of legacy Node.js applications and NPM packages are wired together.

Common Use Cases

  • •Legacy Node.js projects
  • •Dynamic importing (requiring files inside an `if` statement)

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What keywords are used for importing and exporting in CommonJS?

intermediate

  • Is `require()` synchronous or asynchronous?

advanced

  • What is the difference between `module.exports` and `exports`?

Flash Cards

Question

Is require() sync or async?

Click to reveal answer
Answer

It is completely Synchronous! It blocks the thread while it reads the file from the hard drive, compiles it, and caches it. This is why you should only `require()` at the very top of your files, never inside a loop or active request route.

Question

Difference between module.exports and exports?

Click to reveal answer
Answer

`exports` is just a shortcut reference to `module.exports`. If you assign properties to it (`exports.run = () => {}`), it works. But if you try to overwrite it completely (`exports = myFunction`), the reference breaks, and you export nothing. Always use `module.exports = ...` to be safe.