0
0
Node.jsframework~5 mins

CommonJS require and module.exports in Node.js - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does require() do in CommonJS?

require() loads and runs a module file, returning the exported values from that module.

Click to reveal answer
beginner
How do you export a single function or object in CommonJS?

You assign it to module.exports. For example: module.exports = myFunction;

Click to reveal answer
intermediate
What is the difference between exports and module.exports?

exports is a shortcut to module.exports. Reassigning exports breaks the link, so only module.exports controls what is exported.

Click to reveal answer
beginner
Can you require a JSON file using require() in CommonJS?

Yes, require() can load JSON files and returns the parsed object.

Click to reveal answer
intermediate
What happens if you call require() multiple times for the same module?

The module is loaded once and cached. Subsequent require() calls return the cached exports, not re-running the module code.

Click to reveal answer
Which statement correctly exports a function named sayHello in CommonJS?
Aexports = sayHello;
Bmodule.exports = sayHello;
Cexport default sayHello;
Drequire('sayHello');
What does require('./math') return if math.js uses module.exports = { add, subtract }?
AUndefined
BA string with the file path
CAn object with <code>add</code> and <code>subtract</code> functions
DA function named <code>math</code>
If you want to export multiple values, which is the best way in CommonJS?
AUse <code>require()</code> inside the module
BCall <code>exports = value1, value2</code>
CUse <code>export { value1, value2 }</code>
DAssign an object to <code>module.exports</code> with all values
What happens if you do exports = { a: 1 } instead of module.exports = { a: 1 }?
AThe module exports remain unchanged (empty object)
BThe module exports the object { a: 1 }
CAn error is thrown
DThe module exports a function
How does CommonJS handle circular dependencies between modules?
AIt returns a partially loaded module object during the cycle
BIt throws an error immediately
CIt ignores the second require call
DIt reloads the module twice
Explain how require() and module.exports work together in CommonJS modules.
Think about how you share code between files.
You got /4 concepts.
    Describe the difference between exports and module.exports and why it matters.
    Consider what happens if you assign a new object to exports.
    You got /4 concepts.