Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Creating Custom Node.js Modules

Introduction

Node.js is a powerful runtime environment that allows developers to create scalable and efficient applications. Modules are a fundamental part of Node.js, enabling code reuse and organization. In this lesson, we will learn how to create custom Node.js modules.

What are Modules?

Modules in Node.js are small JavaScript files that can be included in other files. They help in organizing code into manageable sections. Node.js has a built-in module system, and you can create your own modules to encapsulate functionality.

Creating Custom Modules

To create a custom Node.js module, follow these steps:

  1. Create a new JavaScript file.
  2. Define your functions or variables in that file.
  3. Export them using module.exports.

Example:


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

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

module.exports = {
    add,
    subtract
};
                

In this example, we created a simple math module that exports two functions, add and subtract.

Exporting Modules

To use your custom module, you need to import it into another file using the require() function.

Example:


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

const sum = mathModule.add(5, 3);
const difference = mathModule.subtract(5, 3);

console.log('Sum:', sum);
console.log('Difference:', difference);
                

Here, we imported the mathModule and used its exported functions.

Best Practices

  • Keep modules focused on a single responsibility.
  • Name your module files clearly to indicate their purpose.
  • Document your modules with comments for better readability.
  • Use default exports for modules that export a single entity.

FAQ

How do I know if I should create a module?

If you have functionality that can be reused across different parts of your application, it's a good candidate for a module.

Can modules depend on other modules?

Yes, modules can require other modules, allowing you to build complex functionalities by composing them together.

What is the difference between module.exports and exports?

module.exports allows you to set what a module exports, while exports is a shorthand reference to module.exports. Be careful to assign to module.exports directly when you want to export a single value.