Node.js Modules

CommonJS and ES modules.

✍️ 2 exercises in this lesson

Node splits code into modules. There are two systems:

  • CommonJS (classic): module.exports = ... and require("./math")
  • ES Modules (modern): export / import. Enable them with "type": "module" in package.json or the .mjs extension.

Built-in modules include fs, path, http, os, events and crypto. Import them with the node: prefix.

Key Takeaways: Node.js Modules

Mastering Node.js Modules helps you write clean and reliable Node.js code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Node.js Modules Code Example

Node.js
// math.js
export const add = (a, b) => a + b;
export default function square(n) { return n * n; }

// app.js
import square, { add } from "./math.js";
import os from "node:os";

console.log(add(2, 3), square(9));
console.log("Platform:", os.platform());
Output
5 81
Platform: win32
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Node.js Modules Practice Exercises

Check what you learned in “Node.js Modules”.

/ 2 solved
Fill in the blank

Import a built-in module with the node: prefix.

import fs from "";
✓ Correct! Not quite. Try again.
Multiple choice

How do you enable ES modules (import/export) in package.json?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services