Thuta Learning
BasicWeb Developmentbeginner

Modules (Require/Export)

Relax. We'll talk through this in plain words — no textbook voice.

As a project grows, keeping all your code in one file makes it hard to find things, hard to edit, and hard to track down errors. In Node.js, you can split files into modules, export with module.exports, and pull them back in with require().

javascript
// File: mathTools.js
function add(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}

module.exports = { add, multiply };

// File: app.js
const mathTools = require('./mathTools');

console.log(mathTools.add(5, 3));
console.log(mathTools.multiply(5, 3));

mathTools.js defines two functions and exports them as an object. In app.js, you pull it in with require('./mathTools') and call mathTools.add() and mathTools.multiply().

You should see
8 15

Info

When importing a local file, if you leave out ./, Node.js might think it's a package instead. So for files inside your own project, use the ./filename format.

Easy traps

  • A common mistake is writing module.export in the singular. The correct form is module.exports—don't drop the s.

Exercise

In real projects, it's common to split things like database helpers, validation helpers, route handlers, and configuration files into their own modules.

You'll know it worked when:

Modules (Require/Export) | Thuta Learning