Node.js ยท Chapter 4 of 43

Node.js Modules

Modules let you organize code into separate reusable files. Node.js treats every file as its own module with its own scope.

You export values from one file and import them into another, keeping large applications maintainable.

Creating a module

Use `module.exports` to expose functions, objects, or values from a file so other files can use them.

Using a module

Use `require()` to import built-in, third-party, or your own modules by path or name.

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

This file exports a single function using module.exports.

Example 2 (javascript)
// app.js
const add = require('./math.js');
console.log(add(2, 3));
Output
5

require() loads the exported function and it can be called directly.

Key points

  • Every Node.js file is its own module.
  • module.exports exposes values from a file.
  • require() imports modules by relative path or name.
  • Modules keep code organized and reusable.
๐Ÿ’ก Note: Built-in modules like `fs` and `path` don't need installation, just `require()`.

๐Ÿ“ Quick Quiz

1. What exposes values from a module?

2. What function imports a module in CommonJS?

3. How do you require your own local file './math.js'?