Q1. What is the CommonJS module system?
CommonJS is the module system used by Node.js by default. It uses require() to import modules and module.exports or exports to export functionality. Each file is treated as a separate module with its own scope. Variables and functions are private unless explicitly exported.
Q2. How do you export from a CommonJS module?
Use module.exports to export a single value (function, object, class). Example:
module.exports = function add(a,b) { return a+b; }; For multiple exports, add properties to exports: exports.add = add; exports.subtract = subtract;. Note: exports is a reference to module.exports.Q3. How do you import with require()?
Use const module = require('./path'). For core modules: require('fs'). For npm packages: require('express'). require() resolves modules based on the rules (core modules first, then node_modules, then relative paths). It returns whatever was exported from the target module.
Q4. What's the difference between exports and module.exports?
exports is a shortcut to module.exports. You can do exports.foo = bar, but you cannot reassign exports directly (exports = {} won't work because it breaks the reference). module.exports is the actual object returned by require(). For exporting a single function/class, use module.exports =.
Q5. How does Node.js resolve modules?
Node.js looks for: built-in core modules first, then if path starts with './' or '../', it's a relative path. Otherwise, it looks in node_modules folders, traversing up the directory tree. For each directory, it checks package.json main field, then index.js. This is the module resolution algorithm.
