Skip to content

Modules and npm

Programming Node.js Difficulty 1/5

Beginning of the lesson

Modules and npm

Split your code into pieces, then borrow code the whole world has written

Big Idea: A module is a file of code you can reuse. Instead of one giant file, you split your program into small files that share code with require/module.exports (or import/export). And npm lets you download ready-made modules other people wrote, so you do not have to build everything yourself.
By the end you will be able to:
  • split code into files with module.exports and require,
  • use the modern import / export style,
  • create a package.json and install packages with npm install.

1. What is a module?

In Node.js, every file is a module. A module keeps its own code private unless it chooses to export something. Another file can then require (import) what was exported.

Analogy: think of a toolbox. Each drawer (module) holds a few tools. When you build something you open only the drawers you need. You do not dump every tool onto the floor at once. Modules keep your project tidy, so each file does one job well.

Splitting code into modules makes it easier to read, reuse, and fix. A 20-line file is much friendlier than a 2000-line file.

2. Exporting and requiring (CommonJS)

The classic Node style is called CommonJS. You share code by putting it on module.exports, and you bring it in with require(). Local files use a path that starts with ./ (the current folder).

First, a module that exports two functions:

// math.js  — a module that exports two helpers
function add(a, b) {
  return a + b;
}
function subtract(a, b) {
  return a - b;
}
module.exports = { add, subtract };

Now another file uses it. require('./math') gives back exactly the object we exported:

// app.js  — uses the math module
const math = require('./math');
console.log(math.add(2, 3));        // 5
console.log(math.subtract(10, 4));  // 6

Run it in the terminal and you see:

$ node app.js
5
6

You can also export a single value directly by replacing the whole module.exports:

// greet.js  — exports ONE thing directly
module.exports = function greet(name) {
  return 'Hello, ' + name + '!';
};
// app.js
const greet = require('./greet');
console.log(greet('Sara'));   // Hello, Sara!

Notice you leave the .js off in require('./greet') — Node adds it for you.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers