Introduction
CommonJS lets you split your code into files and use them together easily. It helps organize code by sharing functions or data between files.
Jump into concepts and practice - no test required
const moduleName = require('modulePath');
module.exports = valueToExport;require() to load a module or file.module.exports to share what a file provides.const math = require('./math');module.exports = function add(a, b) {
return a + b;
};module.exports = {
name: 'Alice',
age: 30
};const fs = require('fs');// math.js
function add(a, b) {
return a + b;
}
module.exports = add;
// app.js
const add = require('./math');
console.log(add(5, 7));require function loads modules synchronously, so it pauses code until the module is ready.module.exports: functions, objects, strings, numbers, etc.require for local files need ./ or ../ to work correctly.require() to load modules and module.exports to share code.require for your own files, and module names for built-in or installed packages.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?