Modules & Exports

Modules are the building blocks of any Node.js application. They allow you to break your code into separate files, making it more organized, reusable, and maintainable.

1. What is a Module?

In Node.js, every file is treated as a separate module. Variables, functions, and classes defined in one file are private to that file unless explicitly "exported."

2. CommonJS (Traditional)

This is the default module system in Node.js. It uses module.exports to export and require() to import.

Exporting (math.js):

const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

module.exports = { add, subtract };

Importing (app.js):

const math = require('./math');

console.log(math.add(5, 3)); // 8

3. ES Modules (Modern)

Standardized in ES6, this system is now natively supported in Node.js using the .mjs extension or by adding "type": "module" to your package.json.

Exporting:

export const multiply = (a, b) => a * b;
export default function welcome() {
  console.log("Welcome to ES Modules!");
}

Importing:

import welcome, { multiply } from './utils.js';

welcome();
console.log(multiply(4, 2)); // 8
Warning: You cannot use require inside an ES Module, and vice versa, without specific configuration. It's best to stick to one system per project.