Performance: CommonJS require and module.exports
This concept affects server-side module loading speed and initial script execution time in Node.js environments.
Jump into concepts and practice - no test required
import fs from 'fs/promises'; async function readFile() { const data = await fs.readFile('file.txt'); console.log(data.toString()); } readFile();
const fs = require('fs'); const data = fs.readFileSync('file.txt'); console.log(data.toString());
| Pattern | Module Loading | Event Loop Blocking | Startup Delay | Verdict |
|---|---|---|---|---|
| CommonJS require with sync operations | Synchronous | Blocks event loop | High delay | [X] Bad |
| ES modules with async operations | Asynchronous | Non-blocking | Low delay | [OK] Good |
module.exports do in a Node.js file?utils.js using CommonJS?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));// greet.js
exports = function() { return 'Hello'; };
// app.js
const greet = require('./greet');
console.log(greet());class User {
constructor(name) {
this.name = name;
}
}
// What should you write here?