Node.js Custom Modules: How to Create, Export, and Utilize Them
What are Custom Modules in Node?
In Node.js, custom modules are user-defined components that contain certain features or logic that are adapted to an application’s requirements. Custom modules are made by developers to better organize and manage their code, as opposed to core modules, which are provided by Node.js itself, or third-party modules, which are accessible through npm. Developers often create their own custom or local modules, such as a ‘Database Module’ for database communication or an ‘Authentication Module’ that includes methods related to authentication and authorization. Let’s understand with some practical scenario:
Creating Custom Module
Step 1 : Open Visual Studio Code Editor.
Step 2: Create a folder named ‘MyApp’. Inside this folder, create a new file named ‘custom_module.js’. In this file, we will create a method called ‘fullname’ that accepts the first name (fname) and last name (lname) as arguments and returns the full name.
function fullName(fname, lname){ return fname+" "+lname; }
Now, your first method will be ready to use. But the question is: how can you use this method in other files? The answer is simple—we need to export the method or file. Without exporting, you can never use this function. Let’s understand more:
Exports the custom modules:
Step 1: Export the function that you want to use in another file. Without exporting, we can’t use any function outside the file. To export the function, you can use ‘module.exports’ as follows
function fullName(fname, lname){ return fname+" "+lname; } module.exports = fullName;
In the above code, “module.exports” is a special object in Node.js used to export functions, objects, or values from a module. This allows the exported content to be made available to other parts of the application that require the module. It is a fundamental feature in Node.js, enabling the creation of modular and reusable code.
Step 2: Use the ‘fullName’ method from the previous file. Create a new file named ‘index.js’ and write the following code in it.
const custom=require('./custom-module'); console.log(custom("Study", "Trigger"));
In the above code, ‘require’ is a built-in function used to load modules, JSON files, or local files into your application. It is a fundamental feature of Node.js that allows developers to include and use code from other files and libraries in a modular and organized way. By using ‘require’, we include our ‘custom-module’ file. The content of that file is assigned to a variable called ‘custom’. You can then call the ‘fullName’ function using this variable. For reference, see the screenshot below with the output:
In the above example, we kept our file as simple as possible for better understanding. I hope that from the information provided above, you can understand how to create a custom module, how to export it, and how to use it. Now, let’s explore another scenario where we export multiple functions. We’ll create a file that performs basic mathematical operations and utilize those functions.
Step 1: Create math.js file with the following functions and exports it :
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) { return a / b; } module.exports = { add, subtract, multiply, divide };
Step 2 : Use the above file and methods inside the index.js file, like :
const maths=require('./maths'); console.log("\nInside maths variable : "); console.log(maths); console.log("\nSum is " +maths.add(7,7)); console.log("Subtraction is " +maths.subtract(7,7)); console.log("Multiplication is " +maths.multiply(7,7)); console.log("Division is " +maths.divide(7,7));
Now, you will see the below output :
Inside maths variable : { add: [Function: add], subtract: [Function: subtract], multiply: [Function: multiply], divide: [Function: divide] } Sum is 14 Subtraction is 0 Multiplication is 49 Division is 1
Let’s explore all the above concepts in Visual Studio Code (VS Code). Please refer to the image below for a visual reference:
Conclude
This article has demonstrated the basics of creating and using custom modules in Node.js. By encapsulating functionality into modules, developers can create more organized and maintainable codebases. I hope from the above article you can understand what a custom module is, and how to export and use these modules. Stay tuned for our next article for a deeper dive into the requirements and real-world scenarios of custom modules.
FAQ’s on Custom Modules in Node
What is a custom module in Node.js?
A custom module in Node.js is a user-defined JavaScript file that encapsulates specific functionality. It can be imported and reused in other files, promoting modularity and code organization.
Why should I use custom modules in my Node.js application?
Custom modules help organize code into manageable sections, improve reusability, and simplify the maintenance and scaling of applications by separating concerns.
How do I create a custom module in Node.js?
To create a custom module, write the desired code in a new JavaScript file and use module.exports to expose the functions or objects you want to make available to other files.
How do I import and use a custom module in another file?
Use the require function to import the custom module, specifying the path to the module file. For example:
const myModule = require(‘./myModule’);
What is the difference between a custom module and a built-in module in Node.js?
Built-in modules are provided by Node.js out of the box (e.g., fs, http), while custom modules are user-defined and created to meet specific needs of the application.
Can I use ES6 import/export syntax in Node.js custom modules?
Yes, Node.js supports ES6 import/export syntax, but it requires using .mjs file extension or setting “type”: “module” in your package.json file. However, traditional CommonJS syntax (require and module.exports) is still widely used.
How do I handle errors in custom modules?
You can handle errors by using try-catch blocks within your functions or by throwing errors and letting the calling code handle them. It’s good practice to document what errors a module might throw.
How do I test my custom modules?
You can test custom modules using unit testing frameworks like Mocha or Jest. Write test cases that import your module and verify its functionality with various inputs and expected outputs.