Bird
Raised Fist0
Node.jsframework~10 mins

CommonJS require and module.exports in Node.js - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - CommonJS require and module.exports
Start: File A wants code from File B
File A calls require('File B')
Node reads File B
Node executes File B
File B sets module.exports
Node returns module.exports to File A
File A uses imported code
End
This flow shows how one file asks for code from another using require, Node runs the second file, and returns what it exports.
Execution Sample
Node.js
/* fileB.js */
module.exports = function() {
  return 'Hello from B';
};

/* fileA.js */
const greet = require('./fileB');
console.log(greet());
File A imports a function from File B using require and then calls it to print a message.
Execution Table
StepActionFilemodule.exports ValueResult/Output
1File A starts and calls require('./fileB')fileA.jsundefinedNo output yet
2Node reads and executes fileB.jsfileB.jsfunction() { return 'Hello from B'; }No output yet
3fileB.js finishes, module.exports set to functionfileB.jsfunction() { return 'Hello from B'; }No output yet
4require returns exported function to fileA.jsfileA.jsfunction() { return 'Hello from B'; }No output yet
5fileA.js calls the imported functionfileA.jsfunction() { return 'Hello from B'; }Output: Hello from B
6Program endsfileA.jsfunction() { return 'Hello from B'; }Output complete
💡 Program ends after fileA.js calls the imported function and prints the output.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5Final
module.exports in fileB.jsundefinedundefinedfunction() { return 'Hello from B'; }function() { return 'Hello from B'; }function() { return 'Hello from B'; }function() { return 'Hello from B'; }
greet in fileA.jsundefinedundefinedundefinedfunction() { return 'Hello from B'; }function() { return 'Hello from B'; }function() { return 'Hello from B'; }
Key Moments - 3 Insights
Why does require return the value of module.exports and not other variables?
Because Node.js specifically returns the module.exports object from the required file, ignoring other local variables. See step 4 in the execution_table where require returns module.exports.
What happens if module.exports is not set in the required file?
If module.exports is not set, it defaults to an empty object {}. So require returns {}. This is why setting module.exports is important to export your code. See step 3 where module.exports is assigned.
Can require execute code in the required file?
Yes, require runs the entire file once to set up module.exports. This is why any code outside functions runs immediately. See step 2 where Node executes fileB.js.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of module.exports in fileB.js after step 3?
AA function that returns 'Hello from B'
Bundefined
CAn empty object {}
DA string 'Hello from B'
💡 Hint
Check the 'module.exports Value' column at step 3 in the execution_table.
At which step does fileA.js receive the exported function from fileB.js?
AStep 2
BStep 5
CStep 4
DStep 1
💡 Hint
Look for when require returns the exported value in the execution_table.
If fileB.js did not set module.exports, what would require('./fileB') return in fileA.js?
Anull
BAn empty object {}
Cundefined
DA function
💡 Hint
Recall the default value of module.exports if not set, as explained in key_moments.
Concept Snapshot
CommonJS modules use module.exports to share code.
Use require('file') to import exports.
Node runs the required file once.
require returns module.exports from that file.
module.exports defaults to {} if not set.
This pattern helps organize Node.js code.
Full Transcript
In Node.js CommonJS modules, one file can use require to import code from another file. When require is called, Node reads and runs the required file. That file sets module.exports to the value it wants to share. Then require returns that module.exports value to the caller. The caller can then use the imported code. If module.exports is not set, it defaults to an empty object. This process allows files to share functions, objects, or values in a clear way.

Practice

(1/5)
1. What does module.exports do in a Node.js file?
easy
A. It deletes the current module from memory.
B. It imports code from another module.
C. It runs the module as a standalone program.
D. It defines what the module shares when required by another file.

Solution

  1. Step 1: Understand module.exports role

    module.exports sets the object or value that other files receive when they use require() on this module.
  2. Step 2: Differentiate from require()

    require() is used to import, while module.exports is used to export code from a module.
  3. Final Answer:

    It defines what the module shares when required by another file. -> Option D
  4. Quick Check:

    module.exports = export code [OK]
Hint: Remember: module.exports shares, require() imports [OK]
Common Mistakes:
  • Confusing require() with module.exports
  • Thinking module.exports runs code
  • Assuming module.exports deletes modules
2. Which of the following is the correct syntax to import a local module named utils.js using CommonJS?
easy
A. const utils = require('./utils');
B. const utils = require('utils');
C. import utils from './utils';
D. const utils = import('./utils');

Solution

  1. Step 1: Identify local module import syntax

    Local files require a relative path starting with './' or '../' in require().
  2. Step 2: Check each option

    const utils = require('./utils'); uses require('./utils'), which correctly imports the local utils.js file. const utils = require('utils'); misses './', so it looks for a package. import utils from './utils'; uses ES module syntax, not CommonJS. const utils = import('./utils'); uses dynamic import, not CommonJS.
  3. Final Answer:

    const utils = require('./utils'); -> Option A
  4. Quick Check:

    Local modules need './' in require() [OK]
Hint: Use './' prefix for local files in require() [OK]
Common Mistakes:
  • Omitting './' for local modules
  • Using ES module import syntax in CommonJS
  • Using import() instead of require()
3. Given the following two files, what will be logged when node app.js runs?

// math.js
module.exports.add = (a, b) => a + b;
module.exports.sub = (a, b) => a - b;

// app.js
const math = require('./math');
console.log(math.add(5, 3));
console.log(math.sub(5, 3));
medium
A. undefined and undefined
B. 8 and 2
C. Error: add is not a function
D. 5 and 3

Solution

  1. Step 1: Understand exports in math.js

    math.js exports two functions: add and sub, which add and subtract two numbers.
  2. Step 2: Trace app.js calls

    app.js requires math.js and calls math.add(5, 3) which returns 8, and math.sub(5, 3) which returns 2.
  3. Final Answer:

    8 and 2 -> Option B
  4. Quick Check:

    5+3=8 and 5-3=2 [OK]
Hint: Check exported function names and call with correct args [OK]
Common Mistakes:
  • Expecting undefined because of wrong export syntax
  • Confusing module.exports with exports shorthand
  • Forgetting to require the module
4. What is the error in the following code snippet?

// greet.js
exports = function() { return 'Hello'; };

// app.js
const greet = require('./greet');
console.log(greet());
medium
A. Cannot find module './greet'.
B. SyntaxError due to missing module.exports.
C. greet is not a function because exports was overwritten incorrectly.
D. No error; it logs 'Hello'.

Solution

  1. Step 1: Analyze exports assignment in greet.js

    Assigning directly to exports replaces the local exports variable but does not change module.exports, so require() gets an empty object.
  2. Step 2: Understand require() result in app.js

    Since module.exports was not changed, greet is an empty object, not a function, so calling greet() causes an error.
  3. Final Answer:

    greet is not a function because exports was overwritten incorrectly. -> Option C
  4. Quick Check:

    Overwrite exports breaks module.exports [OK]
Hint: Always assign to module.exports, not exports directly [OK]
Common Mistakes:
  • Assigning function directly to exports instead of module.exports
  • Expecting exports and module.exports to be the same after reassignment
  • Ignoring that require() returns module.exports
5. You want to export a single class from a module so that requiring it returns the class directly. Which is the correct way to do this in CommonJS?

class User {
  constructor(name) {
    this.name = name;
  }
}

// What should you write here?
hard
A. module.exports = User;
B. exports.User = User;
C. module.exports.User = User;
D. export default User;

Solution

  1. Step 1: Understand exporting a single value

    To export a single class so require() returns it directly, assign it to module.exports.
  2. Step 2: Compare options

    module.exports = User; assigns User directly to module.exports, so require('./module') returns the class. module.exports.User = User; and exports.User = User; export an object with User property, so require() returns an object, not the class itself. export default User; uses ES module syntax, invalid in CommonJS.
  3. Final Answer:

    module.exports = User; -> Option A
  4. Quick Check:

    Single export = module.exports = value [OK]
Hint: Assign single export directly to module.exports [OK]
Common Mistakes:
  • Using exports.User instead of module.exports for single export
  • Mixing ES module syntax with CommonJS
  • Expecting require() to return class when exporting as property