Skip to content
Learn Netverks

Lesson

Step 8/36 22% through track

modules-commonjs

CommonJS modules

Last reviewed May 28, 2026 Content v20260528
Track mode
nodejs_server
Means
Node sandbox
Reading
~1 min
Level
beginner

This lesson

This lesson teaches CommonJS modules: the syntax, APIs, and habits you need before advancing in Node.js.

Module boundaries and npm supply-chain hygiene matter for security reviews and reproducible deploys.

You will apply CommonJS modules in contexts like: REST/GraphQL APIs, BFF layers, CLIs, webhooks, and real-time services (with WebSockets).

Run JavaScript on the Node runner when configured—never mix arbitrary shell commands in lessons. Also use ESM import syntax in the editor—the runner executes main.mjs.

When you can explain the previous lesson's ideas without copying starter code.

Node historically used CommonJS: require() loads modules synchronously; module.exports defines what they expose. Millions of npm packages still use this style.

Export and import (CommonJS)

// greeter.cjs
module.exports = function greet(name) {
  return `Hello, ${name}`;
};

// app.cjs
const greet = require('./greeter.cjs');
console.log(greet('Ada'));

Built-in require

const path = require('node:path');
const fs = require('node:fs');

No import at top level in pure CommonJS files unless using dynamic import().

Playground note

Runnable snippets use ESM. To compare CommonJS in the runner, use createRequire from node:module (see editor code).

Important interview questions and answers

  1. Q: require vs import?
    A: require is sync CommonJS; import is ESM (static, async loading at graph build). Node supports both with configuration.
  2. Q: __dirname in ESM?
    A: Not defined—derive from import.meta.url with fileURLToPath and path.dirname.

Self-check

  1. What does module.exports do?
  2. Why is require synchronous?

Pitfall: Mixing require and top-level await in the same file causes confusion—pick ESM (import) or CommonJS (require) per file in new projects.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • When still use CJS?
  • module.exports pattern?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump