The file exports a string 'Hello from CommonJS' using module.exports.
Step 2: Import and log the exported value
The require call imports the string, so console.log prints it.
Final Answer:
'Hello from CommonJS' -> Option A
Quick Check:
CommonJS require returns module.exports value [OK]
Hint: require() returns module.exports value [OK]
Common Mistakes:
Expecting require to return an object by default
Confusing with ESM import behavior
Thinking require throws error without .js extension
4. What is wrong with this ESM import statement in a Node.js file?
const fs = require('fs');
medium
A. Missing semicolon at the end
B. require is not defined in ESM modules
C. fs module cannot be imported in Node.js
D. Should use import fs from 'fs' instead
Solution
Step 1: Identify module system used
The code uses require which is CommonJS syntax, but in ESM modules, require is not available.
Step 2: Understand ESM import rules
ESM modules must use import statements; require is undefined.
Final Answer:
require is not defined in ESM modules -> Option B
Quick Check:
require() undefined in ESM [OK]
Hint: require() is undefined in ESM modules [OK]
Common Mistakes:
Thinking require works in ESM without extra setup
Confusing missing semicolon as error
Believing fs cannot be imported in Node.js
5. You want to write a Node.js module that can be imported both by CommonJS and ESM users without errors. Which approach is best?
hard
A. Use module.exports and add a separate export default for ESM
B. Write only CommonJS syntax and use dynamic import() in ESM
C. Use a dual package approach with conditional exports in package.json
D. Write only ESM syntax and rename file to .mjs
Solution
Step 1: Understand compatibility challenges
CommonJS and ESM have different import/export systems, so a single file often can't serve both seamlessly.
Step 2: Use Node.js dual package support
Node.js supports conditional exports in package.json to provide separate entry points for CommonJS and ESM consumers.
Step 3: Evaluate other options
Use module.exports and add a separate export default for ESM mixes syntaxes which doesn't work reliably, C requires dynamic import in consumers, D limits to ESM-only.
Final Answer:
Use a dual package approach with conditional exports in package.json -> Option C