Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

Creating Custom Modules in Node.js

Learn how to create your own reusable modules in Node.js. Understand how to separate program logic into different files, export functions and variables, import modules, and build a practical application using custom modules.

1. What Is a Custom Module?

A custom module is a JavaScript file created by a developer to perform a particular task in an application. Instead of writing all the program logic in one file, we can divide the application into smaller files called modules.

For example, a student management application may contain separate files for student details, marks calculation, and the main program. Each file can handle its own responsibility.

Node.js allows us to create custom modules and reuse their functionality in other files. We can use CommonJS syntax with module.exports and require(), or ES Module syntax with export and import.

Example

JavaScript - math.js
function add(a, b) {
    return a + b;
}

module.exports = add;

In this example, we created our own function named add(). The statement module.exports = add makes the function available to another CommonJS module.

Definition: A custom module is a developer-created file that contains reusable functionality and can be used by other files in a Node.js application.

2. Why Do We Create Custom Modules?

As an application grows, writing every function in one file makes the program difficult to understand and maintain. Custom modules help us organize the code properly.

  • Code Reusability: Write a function once and use it in multiple files.
  • Code Organization: Keep related functions and logic together.
  • Easy Maintenance: Update a particular feature in its own file.
  • Readability: Keep the main application file shorter and easier to understand.
  • Separation of Responsibilities: Keep calculation, validation, and data-handling logic separate.
  • Testing: Test individual functions and modules independently.

3. Custom Module Working Diagram

A custom module is created in one file, exported, and then imported into another file. The main program can call the imported function and use its result.

Step 1: Create a Module

Create a file such as math.js and define reusable functions.

↓
Step 2: Export Functionality

Use module.exports to expose the function.

↓
Step 3: Import the Module

Use require("./math") in another file.

↓
Step 4: Use the Function

Call the imported function and display its result.

4. Creating Your First Custom Module

Let us create a simple custom module that performs addition. We will use two JavaScript files: math.js and app.js.

Step 1: Create the Project Folder

Create a folder named CustomModuleExample. Inside this folder, create the following two files.

Project Structure
CustomModuleExample/
    math.js
    app.js

Step 2: Write the Custom Module

Open math.js and write the following program.

JavaScript - math.js
function add(a, b) {
    return a + b;
}

module.exports = add;

Explanation:

  • function add(a, b) defines a function with two parameters.
  • return a + b returns the sum of the two values.
  • module.exports = add exports the function so another CommonJS file can use it.

Step 3: Import the Custom Module

Open app.js. Use require() to load the exported function.

JavaScript - app.js
const add = require("./math");

const result = add(10, 20);

console.log("Addition:", result);

Output

Output
Addition: 30

Explanation: The require("./math") statement loads the function exported from math.js. We store that function in the variable add, call it with the values 10 and 20, and display the returned result using console.log().

5. Creating a Module with Multiple Functions

A custom module can export multiple functions. We can group related operations in one file and export them together as an object.

Step 1: Create calculator.js

JavaScript - calculator.js
function add(a, b) {
    return a + b;
}

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

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

function divide(a, b) {
    if (b === 0) {
        return "Cannot divide by zero";
    }

    return a / b;
}

module.exports = {
    add,
    subtract,
    multiply,
    divide
};

Explanation: We define four functions for addition, subtraction, multiplication, and division. The exported object contains all four functions. The division function also checks whether the second number is zero before performing the calculation.

Step 2: Use calculator.js in app.js

JavaScript - app.js
const calculator = require("./calculator");

console.log("Addition:", calculator.add(20, 10));
console.log("Subtraction:", calculator.subtract(20, 10));
console.log("Multiplication:", calculator.multiply(20, 10));
console.log("Division:", calculator.divide(20, 10));
console.log("Division by zero:", calculator.divide(20, 0));

Output

Output
Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2
Division by zero: Cannot divide by zero

Explanation: The variable calculator holds the object returned by require("./calculator"). We access each exported function using dot notation, such as calculator.add() and calculator.multiply().

6. Import Specific Functions Using Destructuring

If we need only selected functions from an exported object, JavaScript object destructuring allows us to extract those functions directly.

Example

JavaScript - app.js
const { add, multiply } = require("./calculator");

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

Output

Output
8
15

Here, add and multiply are extracted from the object exported by calculator.js. We can call them directly without writing calculator.add() or calculator.multiply().

Remember: The names inside the destructuring statement must match the exported property names unless you explicitly use aliases.

7. Creating a Student Custom Module

Custom modules are useful in real applications too. Let us create a student module that returns student information.

Step 1: Create student.js

JavaScript - student.js
function getStudentDetails(name, course, marks) {
    return {
        name: name,
        course: course,
        marks: marks
    };
}

module.exports = getStudentDetails;

The getStudentDetails() function accepts a student's name, course, and marks. It returns an object containing these three properties.

Step 2: Create app.js

JavaScript - app.js
const getStudentDetails = require("./student");

const student = getStudentDetails(
    "Samadhan",
    "Node.js",
    85
);

console.log("Student Name:", student.name);
console.log("Course:", student.course);
console.log("Marks:", student.marks);

Output

Output
Student Name: Samadhan
Course: Node.js
Marks: 85

Explanation: The main file imports the student function, passes the student's information as arguments, and receives the returned object. It then accesses the object's properties to display the details.

8. Student Module Program Flow

This diagram shows how the student module and the main application work together.

student.js

Defines and exports getStudentDetails().

↓
app.js

Imports the function using require("./student").

↓
Pass Student Information

Name, course, and marks are passed to the function.

↓
Returned Student Object

The application reads and displays the student details.

9. Creating a Custom Module Using ES Modules

Node.js also supports ES Modules. In this module system, we use export to share functionality and import to use it in another file.

For this example, use the .mjs extension for both files so Node.js treats them as ES Modules.

Step 1: Create message.mjs

JavaScript - message.mjs
export function getWelcomeMessage(name) {
    return "Welcome to Node.js, " + name + "!";
}

Step 2: Create app.mjs

JavaScript - app.mjs
import { getWelcomeMessage } from "./message.mjs";

console.log(getWelcomeMessage("Student"));

Output

Output
Welcome to Node.js, Student!

In this example, the export keyword makes the function available to other ES Modules. The import statement loads the named export into app.mjs.

Important: Do not mix CommonJS and ES Module syntax without checking your project's module configuration. The CommonJS examples above use require() and module.exports, whereas the ES Module example uses import and export.

10. How to Run a Custom Module Program

Follow these steps to execute the CommonJS calculator program.

  1. Create a folder named CustomModuleExample.
  2. Save the calculator functions in calculator.js.
  3. Save the main program in app.js.
  4. Open a terminal in the project folder.
  5. Execute the main file using the Node.js command.

Terminal Command

Terminal
node app.js

Node.js executes app.js. When it reaches require("./calculator"), it loads the local calculator module and makes its exported functionality available to the main program.

Note: The relative path ./calculator refers to the calculator.js file in the same folder for this CommonJS example. Make sure both files are saved in the expected location.

11. Common Mistakes When Creating Custom Modules

Mistake Correct Approach
Forgetting to export a function. Use module.exports or an appropriate ES Module export.
Using an incorrect file path. Check the relative path and filename.
Calling a function that was not exported. Verify the exported values and function names.
Using import in a CommonJS example without the correct setup. Use the module syntax supported by the file's configuration.
Keeping all logic in one large file. Separate reusable functionality into focused modules.
Assuming an imported function automatically runs. Call the function explicitly when its result is needed.

12. Practice Tasks

Task 1: Create a Calculator Module

Create a file named calculator.js containing addition, subtraction, multiplication, and division functions. Export the functions and use them from app.js.

Challenge: Add a condition to handle division by zero.

Task 2: Create a Student Module

Create a file named student.js that exports a function accepting a student's name, course, and marks. Import the function into app.js and display all three values.

Task 3: Create a Welcome Module

Create a module that exports a function named getWelcomeMessage(). The function should accept a name and return a welcome message. Import and call it from another file.

Important Points

  • A custom module is a file created by the developer to organize reusable functionality.
  • CommonJS uses module.exports to export values and require() to import them.
  • A module can export one function or an object containing multiple functions.
  • ES Modules use export and import.
  • Relative paths such as ./calculator refer to local files.
  • Separating code into modules improves readability, reusability, and maintainability.

Summary

Custom modules in Node.js allow developers to organize application logic into separate, reusable JavaScript files. CommonJS uses module.exports to expose functionality and require() to load it into another file, while ES Modules use export and import. We can create modules for calculations, student information, and other application features, then reuse their functions wherever required. Creating custom modules improves code organization, readability, maintainability, and code reusability in Node.js applications.