You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
As applications grow, keeping all code in a single file becomes unmanageable. Node.js solves this with a module system that lets you split code into separate files and share functionality between them.
A module is simply a file. Every file in a Node.js application is treated as its own module with its own scope. Variables and functions defined in one file are not visible to other files unless explicitly exported.
The traditional Node.js module format is CommonJS (CJS). You export values using module.exports and import them using require().
// math.js — defining a module
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = { add, subtract };
// app.js — using the module
const math = require("./math");
console.log(math.add(5, 3)); // 8
console.log(math.subtract(10, 4)); // 6
The path ./math is relative to the current file. Node.js automatically appends .js if the extension is omitted.
You can also add properties directly to the exports object:
// greet.js
exports.hello = function (name) {
return "Hello, " + name + "!";
};
exports.goodbye = function (name) {
return "Goodbye, " + name + "!";
};
Be careful: reassigning exports directly (e.g. exports = function() {}) breaks the reference. Use module.exports for that case.
Node.js ships with built-in core modules that you can require by name (no path needed):
const path = require("path");
const os = require("os");
const fs = require("fs");
console.log(path.join("/users", "john", "file.txt")); // /users/john/file.txt
console.log(os.platform()); // 'darwin', 'linux', etc.
Packages installed via npm are required by their package name:
const express = require("express");
const lodash = require("lodash");
Node.js looks for these in the node_modules folder in your project.
Modern JavaScript supports ES Modules using import and export syntax. Node.js supports ESM in files with the .mjs extension or when "type": "module" is set in package.json:
// math.mjs
export function add(a, b) { return a + b; }
// app.mjs
import { add } from "./math.mjs";
console.log(add(2, 3)); // 5
Most existing Node.js codebases still use CommonJS. Both systems are important to understand as you work with different projects and packages.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.