SyntaxStudy
Sign Up
Node.js CommonJS Modules (require / exports)
Node.js Beginner 9 min read

CommonJS Modules (require / exports)

CommonJS is the original module system in Node.js. Each file is a module. You export values with module.exports and import them with require().

CommonJS modules are loaded synchronously, which is fine for server-side code.

Example
// --- math.js (exporting) ---
function add(a, b) {
    return a + b;
}

function subtract(a, b) {
    return a - b;
}

const PI = 3.14159;

// Export an object with multiple values:
module.exports = { add, subtract, PI };

// --- app.js (importing) ---
const { add, subtract, PI } = require('./math');

console.log(add(10, 5));       // 15
console.log(subtract(10, 5));  // 5
console.log(PI);               // 3.14159

// Import a single default export:
// module.exports = function greet(name) { ... };
// const greet = require('./greet');

// Built-in modules use the same require() syntax:
const path = require('path');
const os   = require('os');

console.log(path.join(__dirname, 'files', 'data.txt'));
console.log(os.homedir());