Profile Photo

Modularization in Nodejs

Created on: Aug 26, 2024

Modularization_in_Nodejs Modularization in Node.js is a fundamental concept that allows you to structure your code into manageable, reusable pieces.

Node.js uses CommonJS as its module format which simply allows developers to import modules using require() and export functionality from a module using module.exports

// math.js function add(a, b) { return a + b; } function subtract(a, b) { return a - b; } module.exports = { add, subtract, };
// app.js const math = require("./math"); console.log(math.add(2, 3)); // Output: 5 console.log(math.subtract(5, 2)); // Output: 3

In newer versions of Node.js, you can use ES6 module syntax (import/export) instead of CommonJS (require/module.exports).

// addTwo.mjs function addTwo(num) { return num + 2; } export { addTwo };
// app.mjs import { addTwo } from "./addTwo.mjs"; // Prints: 6 console.log(addTwo(4));