#
Create User-Defined Modules
This tutorial explains to you how to create your own module in Node.js. This article provides you with an example as well.
A Node.js Module is a library of functions that could be used in Node.js. These modules are generally small and include functionalities related to a domain. For the list of Node.js modules, you can go here.
There are 3 module type in Node.js:
- Built-in modules (provided by Node.js installation)
- User-defined modules (created by the user)
- Third party modules (generally available on the Internet)
Here are the steps for creating a User-defined module:
1) Create a .js file which contains the Custom module:
// Returns addition of two numbers
exports.add = function (a, b) {
return a+b;
};
// Returns difference of two numbers
exports.subtract = function (a, b) {
return a-b;
};
Info
The functions we add to the Custom Module must be defined with "exports" in front of the function name.
- Create the main application which calls the User-Defined (Custom) Module:
var cm = require('./customModule');
var a=100, b=10;
console.log("Addition : "+cm.add(a,b));
console.log("Subtraction : "+cm.subtract(a,b));
console.log("My Application has been finished !");
Here are the files we have created:
And here is the execution of the main application:
Info
- a custom module is loaded using the syntax as for a regular module: "var cm = require('./customModule');".
- in the require command we need to put the name of the file which keeps the module functions.