</>
Skip to content
Node.js lessons (7/44)

Node.js — Modules

CommonJS

// 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));

ES Modules

// math.mjs
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }

// app.mjs
import { add, subtract } from './math.mjs';
console.log(add(2, 3));

package.json for ES Modules

{
  "type": "module"
}

Built-in Modules

ModuleDescription
fsFile system
pathFile paths
httpHTTP server
httpsHTTPS server
urlURL parsing
osOperating system
eventsEvent emitter
streamStreams
const fs = require('fs');
const path = require('path');
const http = require('http');

Export Patterns

// Single export
module.exports = function() {};

// Multiple exports
module.exports = {
    func1: function() {},
    func2: function() {}
};

// Export class
module.exports = class MyClass {};

Mini Practice

  1. Create a module with CommonJS
  2. Create a module with ES Modules
  3. Use built-in modules
  4. Export functions and classes

Up Next

Continue with NPM — package management.

Related Topics

Frequently Asked Questions about Modules

What is Modules in Node.js?

Modules is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Modules?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Modules.

Why is Modules important in Node.js?

Modules is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.