Lesson 7 of 50 – Node.js Modules
14%
14%

Node.js Modules

Modules in Node.js allow us to organize JavaScript code into separate files and reuse functions, variables, classes, and other functionality.

Instead of writing an entire application in one large file, we can divide it into smaller, manageable modules. This makes our code easier to understand, maintain, and reuse.

Remember: A module is a reusable unit of code. Node.js supports built-in modules, CommonJS modules, and ECMAScript (ES) modules.

What Is a Module?

A module is a file or a collection of code that provides specific functionality. For example, one module can perform mathematical calculations while another can manage student information.

Example: Project Structure
MyNodeProject/
├── app.js
├── math.js
└── student.js

In this project, math.js can contain calculation functions, while student.js can contain student-related functionality.

Advantages of Modules

1. Code Reusability

Write a function once and reuse it in different files.

2. Better Organization

Divide a large application into smaller files with clear responsibilities.

3. Easier Maintenance

Update one module without unnecessarily changing unrelated code.

Types of Modules in Node.js

1. Built-in Modules

Built-in modules are provided by Node.js. They offer functionality without requiring you to install a separate package.

  • fs – File system operations.
  • path – Working with file and directory paths.
  • os – Operating-system information.
  • http – Creating HTTP servers and working with HTTP.
2. Local Modules

Local modules are files created by you inside your own project. You can export functionality from one file and import it into another.

3. Third-Party Packages

Third-party packages are created and shared by other developers. They are commonly installed using NPM, for example, Express.js and Lodash.

Example 1: Using a Built-in Module

Let's use the built-in os module to display information about the operating system.

app.js
const os = require('node:os');

console.log("Platform:", os.platform());
console.log("Architecture:", os.arch());
Example Output
Terminal Output
Platform: win32
Architecture: x64

The output above is an example from a Windows computer. Your results may differ depending on your operating system and hardware.

Explanation
  • require('node:os') loads the built-in OS module using CommonJS syntax.
  • os.platform() returns the operating-system platform identifier.
  • os.arch() returns the architecture of the Node.js process.

Example 2: Create Your Own Module

Now let's create a local module named math.js. It will contain a function for adding two numbers.

Step 1: Create math.js
math.js
function add(a, b) {
    return a + b;
}

module.exports = add;

The module.exports statement makes the add function available to other CommonJS modules.

Step 2: Import the Module in app.js
app.js
const add = require('./math');

console.log(add(10, 20));
console.log(add(5, 15));
Output
Terminal Output
30
20
Explanation
  • require('./math') loads the local module from math.js.
  • module.exports = add exports the function.
  • add(10, 20) returns 30.
  • add(5, 15) returns 20.
Important: The ./ indicates a local file relative to the current module. It is not the same as importing an NPM package by its package name.

Example 3: Export Multiple Functions

A module can export multiple functions using an object.

Step 1: Create math.js
math.js
function add(a, b) {
    return a + b;
}

function subtract(a, b) {
    return a - b;
}

module.exports = {
    add,
    subtract
};
Step 2: Use the Functions
app.js
const math = require('./math');

console.log("Addition:", math.add(20, 10));
console.log("Subtraction:", math.subtract(20, 10));
Output
Terminal Output
Addition: 30
Subtraction: 10

Example 4: Import a Built-in File System Module

Node.js also provides a built-in file system module. Here is a simple example that creates a text file.

app.js
const fs = require('node:fs');

fs.writeFileSync('message.txt', 'Hello from Node.js!');

console.log("File created successfully.");
Output
Terminal Output
File created successfully.

When you run this program, it creates or replaces message.txt in the current working directory with the specified text. Be careful: writeFileSync() overwrites an existing file with the same name.

CommonJS and ES Modules

Node.js supports two major JavaScript module systems: CommonJS and ECMAScript Modules (ESM).

CommonJS

CommonJS commonly uses require() and module.exports.

const add = require('./math');

console.log(add(2, 3));
ES Modules

ES Modules use import and export.

import { add } from './math.js';

console.log(add(2, 3));

This example assumes math.js exports a named function and the project is configured to use ES modules, for example with "type": "module" in package.json.

Note: We will study CommonJS and ES Modules in more detail in the upcoming lessons.

Common Mistakes

1. Incorrect File Path

If your module is in the same directory as app.js, use:

require('./math');
2. Forgetting to Export

A function declared in one CommonJS file is not automatically available in another file. Export it using module.exports or exports.

3. Mixing Module Systems Incorrectly

CommonJS and ES Modules use different syntax and configuration. Follow the module system configured for your project.

Practical Assignment

Practice Tasks
  1. Create a project folder named ModulePractice.
  2. Create a file named math.js.
  3. Write an addition function and export it.
  4. Import the function into app.js.
  5. Calculate the sum of 100 and 200.
  6. Add a subtraction function to the module.
  7. Export both functions and use them in app.js.
  8. Try the built-in os module to display your operating-system platform.
💡 Remember
Modules help you organize and reuse code. Node.js provides built-in modules, supports local modules, and allows you to install third-party packages using NPM.

🧠 Quiz

1. What is a module in Node.js?

2. Which statement exports a function in CommonJS?

3. Which prefix indicates a relative local module path?