Creating and Exporting Custom Modules

Tutorial 3 of 5

1. Introduction

Goal

This tutorial will guide you through the process of creating and exporting your custom modules in Node.js.

Learning Outcomes

By the end of this tutorial, you will be able to:
1. Create your own custom modules in Node.js.
2. Export your custom modules for use in other parts of your application.

Prerequisites

Basic knowledge of JavaScript and Node.js is necessary. Familiarity with ES6 syntax will be beneficial but not mandatory.

2. Step-by-Step Guide

Modules in Node.js are standalone JavaScript files that export functionalities to be used in other files. They help in organizing code into separate parts with a well-defined interface.

Creating a Module

To create a module, we simply create a new JavaScript file and write our module code into it.

Exporting a Module

To make the functionalities available to other files, we use module.exports or exports.

3. Code Examples

Example 1: Creating a simple module

Let's create a simple module that exports a function to add two numbers.

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

module.exports = add;

In this example, we define a function add and then export it using module.exports.

Example 2: Using the module

To use the module we created, we use require.

// main.js
const add = require('./add');

console.log(add(1, 2));  // Outputs: 3

In this example, we import the add module using require and then use it to add two numbers.

4. Summary

In this tutorial, we learned how to create and export custom modules in Node.js. Creating modules helps us organize our code into separate parts with a well-defined interface.

5. Practice Exercises

  1. Create a module that exports a function to subtract two numbers. Use the module in a separate file.

  2. Create a module that exports an object with four functions: add, subtract, multiply, divide. Each function should take two numbers and perform the respective operation. Use this module in a separate file.

Solutions

  1. Subtraction module:
// subtract.js
function subtract(a, b) {
  return a - b;
}

module.exports = subtract;

Use the module:

// main.js
const subtract = require('./subtract');

console.log(subtract(5, 3));  // Outputs: 2
  1. Calculator module:
// calculator.js
module.exports = {
  add: (a, b) => a + b,
  subtract: (a, b) => a - b,
  multiply: (a, b) => a * b,
  divide: (a, b) => a / b
};

Use the module:

// main.js
const calculator = require('./calculator');

console.log(calculator.add(1, 2));       // Outputs: 3
console.log(calculator.subtract(5, 3));  // Outputs: 2
console.log(calculator.multiply(2, 3));  // Outputs: 6
console.log(calculator.divide(8, 2));    // Outputs: 4