Lesson 4 of 30

Node.js Modules

Chapter 4

Node.js Modules

Understand modules and how Node.js organizes application code.

Theory

A module is a reusable piece of code that can be imported into another file. Node.js applications are commonly divided into modules to make code easier to maintain. A module can export: • Functions • Objects • Variables • Classes Modules help organize large applications into smaller reusable components.

Example

Node.js Example
// math.js

function add(a, b) {
  return a + b;
}

module.exports = {
  add
};

// app.js

const math = require("./math");

console.log(math.add(10, 20));

Output

The add function is exported from one module and used in another module.

Practice

Create a custom module containing addition and subtraction functions.

Interview Questions

1.

What is a module in Node.js?

2.

Why are modules useful?

3.

How do you export code from a module?

Quick Quiz

Which option best matches this chapter?

A.A reusable piece of code
B.A database table
C.A CSS selector
D.A browser extension

Answer: A reusable piece of code