Modules Overview

Node code is organized into reusable files called modules.

Syntaxconst fs = require('fs');

A module is simply a file of JavaScript whose code can be shared with other files. Splitting a program into modules keeps it organized and reusable.

Three kinds of modules

  • Core modules — built into Node, like fs, http, and path. No install needed.
  • Local modules — your own files, loaded by their path (./utils).
  • npm modules — third-party packages installed into node_modules.

You bring a module into your file with require() (CommonJS) or import (ES modules).

Example

Example · javascript
// Core module (built in)
const path = require('path');

// Local module (your own file)
const helpers = require('./helpers');

// npm module (installed with npm install)
const express = require('express');

console.log(path.extname('report.pdf')); // .pdf

When to use it

  • A large Express app splits route handlers, middleware, and utilities into separate module files so teams can work in parallel without merge conflicts.
  • A shared validation library is published as an npm package and required by both the API server and the admin dashboard via `require()`.
  • An internal CLI tool uses `module.exports` to expose a `run()` function that can be both executed directly and imported in tests.

More examples

Export and import a value

Shows the basic CJS module pattern: export an object from one file and require it in another.

Example · js
// math.js
function add(a, b) { return a + b; }
module.exports = { add };

// app.js
const { add } = require('./math');
console.log(add(2, 3)); // 5

Default export function

Exports a single function as the module's default export and imports it directly.

Example · js
// greet.js
module.exports = function greet(name) {
  return `Hello, ${name}!`;
};

// app.js
const greet = require('./greet');
console.log(greet('Alice'));

Require a built-in module

Requires two Node.js built-in modules — no installation needed, just `require` by name.

Example · js
const os = require('os');
const path = require('path');

console.log('Platform:', os.platform());
console.log('Home dir:', os.homedir());
console.log('Joined:', path.join('/usr', 'local', 'bin'));

Discussion

  • Be the first to comment on this lesson.